dictionary that have functions with arguments

Mike Meyer mwm at mired.org
Wed Nov 2 00:50:46 EST 2005


s99999999s2003 at 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 <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list