473,384 Members | 1,854 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,384 software developers and data experts.

dictionary that have functions with arguments

hi
i have a dictionary defined as

execfunc = { 'key1' : func1 }

to call func1, i simply have to write execfunc[key1] .
but if i have several arguments to func1 , like

execfunc = { 'key1' : func1(**args) }

how can i execute func1 with variable args?
using eval or exec?

thanks

Nov 2 '05 #1
8 1339
<s9************@yahoo.com> wrote:
hi
i have a dictionary defined as

execfunc = { 'key1' : func1 }

to call func1, i simply have to write execfunc[key1] .
No, you ALSO have to write ( ) [[parentheses]] after that. MENTIONING a
function doesn't call it, it's the parentheses that do it.
but if i have several arguments to func1 , like

execfunc = { 'key1' : func1(**args) }

how can i execute func1 with variable args?
using eval or exec?


Too late: by having those parentheses there you've ALREADY called func1
at the time the execfunc dict was being built.

Suggestion: parenthesise differently to make tuples:

execfunc = { 'key1' : (func1, ()),
'key2' : (func2, args) }

now, something like:

f, a = execfunc[k]
f(**a)

will work for either key.
Alex
Nov 2 '05 #2


s9************@yahoo.com wrote:
hi
i have a dictionary defined as

execfunc = { 'key1' : func1 }

to call func1, i simply have to write execfunc[key1] .
but if i have several arguments to func1 , like

execfunc = { 'key1' : func1(**args) }

how can i execute func1 with variable args?
using eval or exec?

thanks


Eval or exec aren't needed. Normally you would just do...

execfunc['key1'](**args)

If your arguments are stored ahead of time with your function...

execfunc = {'key1':(func1, args)}

You could then do...

func, args = execfunc['key1']
func(**args)

Cheers,
Ron
Nov 2 '05 #3
s9************@yahoo.com writes:
hi
i have a dictionary defined as

execfunc = { 'key1' : func1 }

to call func1, i simply have to write execfunc[key1] .
but if i have several arguments to func1 , like

execfunc = { 'key1' : func1(**args) }

how can i execute func1 with variable args?
using eval or exec?


Whenever you think "should I use eval or exec for this", you should
*immediately* stop and think "What am I doing wrong?".

Others have suggested using a tuple to hold the function and
arguments, and pointed out the mistake in your invocation.

Whenever you're thinking about doing an evalu with a fixed string, you
can replace it with a lambda. That looks like:
execfunc = dict(key1 = lambda: func1('hello'))
def func1(x): print x .... execfunc['key1']() hello
You can use the tuple format, and then use apply and the extended call
syntax to keep it in one line:
execfunc = dict(key1 = (func1, ('hello',)))
apply(*execfunc['key1']) hello


Note that applly is depreciated - you're supposed to use the extended
call syntax instead. This particular use case for apply can't be
handled by the extended call syntax.

Using dictionaries instead of a fixed arg is a trivial change to both
these examples.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Nov 2 '05 #4
Ron Adam wrote:

Eval or exec aren't needed. Normally you would just do...

execfunc['key1'](**args)

If your arguments are stored ahead of time with your function...

Committed revision 41366.
You could then do...

func, args = execfunc['key1']
func(**args)


Interesting that both Ron and Alex made the same mistake. Hmmm, makes
me wonder if they are two people or not...

If args is a tuple, it should be:

func(*args)

If you want the full generality and use keyword args:

func(*args, **kwargs)

kwargs would be a dictionary with string keys.

E.g.,

execfunc = {'key1':(func1, (1,), {'keyarg': 42})}

HTH,
n

Nov 2 '05 #5
Alex Martelli wrote:
execfunc = { 'key1' : (func1, ()),
'key2' : (func2, args) }

now, something like:

f, a = execfunc[k]
f(**a)

will work for either key.


Shouldn't func1's args be a dictionary, not a tuple?
Nov 2 '05 #6


Neal Norwitz wrote:
Ron Adam wrote:
Eval or exec aren't needed. Normally you would just do...

execfunc['key1'](**args)

If your arguments are stored ahead of time with your function...

Committed revision 41366.
Committed revision 41366 ?

You could then do...

func, args = execfunc['key1']
func(**args)

Interesting that both Ron and Alex made the same mistake. Hmmm, makes
me wonder if they are two people or not...

If args is a tuple, it should be:

func(*args)


No mistake at all, I simply reused the name the OP used in his example.
execfunc = { 'key1' : func1(**args) }


There's no rule that says you can't name a dictionary 'args', and it
wasn't part of the posters question.

If you want the full generality and use keyword args:

func(*args, **kwargs)


I tend to prefer (*args, **kwds) myself. There are also times when I
don't want full generality. In many cases the less general your
arguments are to a function the easier it is to catch errors.

Cheers,
Ron


Nov 2 '05 #7
Leif K-Brooks <eu*****@ecritters.biz> wrote:
Alex Martelli wrote:
execfunc = { 'key1' : (func1, ()),
'key2' : (func2, args) }

now, something like:

f, a = execfunc[k]
f(**a)

will work for either key.


Shouldn't func1's args be a dictionary, not a tuple?


Yes, to call with ** a must be a dict (so {}, not ()).
Alex
Nov 2 '05 #8
On 1 Nov 2005 20:02:41 -0800, s9************@yahoo.com
<s9************@yahoo.com> wrote:
hi
i have a dictionary defined as

execfunc = { 'key1' : func1 }


##################

def __HELLO(x=' '):
print 'HELLO',x

def __BYE(x=' '):
print 'BYE',x

def __PRINT(x=None, y=None):
print 'PRINT',x,y

cmds = { 'HELLO' : __HELLO,
'BYE' : __BYE,
'PRINT' : __PRINT,
}

a = 'HELLO JOE'
b = a.split()

if cmds.has_key(b[0]):
cmds[b[0]](b[1])
# -> HELLO JOE

cmds[b[0]]()
# -> HELLO

cmds['BYE']('TOM')
# -> BYE TOM

cmds['PRINT']( 'TOM','JOE' )
# -> PRINT TOM JOE

cmds['PRINT']
# -> *No output - No exception

#####################

Inside a class use

cmds = { 'HELLO' : self.__HELLO, # etc

def __HELLO(self, x=' '): #etc
HTH :)
Nov 2 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Jack Carter | last post by:
I have been delegated to produce a tool that has python embedded in it. The desire is to have a command line interface that inherits all the python scripting functionality so people can use the...
15
by: Stefan Behnel | last post by:
Hi! I'm trying to do this in Py2.4b1: ------------------------------- import logging values = {'test':'bla'} logging.log(logging.FATAL, 'Test is %(test)s', values)...
125
by: Raymond Hettinger | last post by:
I would like to get everyone's thoughts on two new dictionary methods: def count(self, value, qty=1): try: self += qty except KeyError: self = qty def appendlist(self, key, *values): try:
16
by: David Bear | last post by:
I know there must be a better way to phrase this so google understands, but I don't know how.. So I'll ask people. Assume I have a list object called 'alist'. Is there an easy way to create a...
4
by: Noah | last post by:
I have a dictionary that I would like to expand to satisfy a function's agument list. I can used the ** syntax to pass a dictionary, but this only works if each key in the dictionary matches an...
90
by: Christoph Zwerschke | last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in...
4
by: 63q2o4i02 | last post by:
Hi, I'm writing a hand-written recursive decent parser for SPICE syntax parsing. In one case I have one function that handles a bunch of similar cases (you pass the name and the number of...
7
by: Bill Woodruff | last post by:
I've found it's no problem to insert instances of named delegates as values into a generic dictionary of the form : private Dictionary<KeyType, DelegatemyDictionary = new Dictionary<KeyType,...
0
by: James Mills | last post by:
On Fri, Oct 31, 2008 at 8:49 AM, mark floyd <emfloyd2@gmail.comwrote: Mark, this is correct behavior. You have 3 positional arguments in the function definition. You _must_ aupply _all_ 3 of...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.