dictionary that have functions with arguments

Alex Martelli aleax at mail.comcast.net
Tue Nov 1 23:20:58 EST 2005


<s99999999s2003 at 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



More information about the Python-list mailing list