Calling function keywords from a dictionary
Peter Otten
__peter__ at web.de
Fri Mar 26 08:11:15 EST 2004
Alexander Straschil wrote:
> I have a dic like
> dic = {
> 'action': 'myfunc',
> 'x': 1,
> 'y': 2,
> 'z': 3
> }
> and I have a method
> def myfunc(x, y, z, a=None, b=None)
I assume you forgot the self parameter.
>
> What I want to do ist calling the method defined in 'action' with
> all the named parameter, also instead of
> self.myfunct(x=1, y=2, z=3)
> I want to do
> f = getattr(self, dic['action'])
> f(named parameter from the dic)
>>> class A:
... def first(self, x, y, z, a=None, b=None):
... print "calling first"
... print "x =", x
... print "a =", a
...
>>> a = A()
>>> d = dict(action="first", x=1, y=2, z=3)
>>> d
{'y': 2, 'x': 1, 'z': 3, 'action': 'first'}
# as a sideeffect, pop() removes "action" from the dictionary
# make a copy if that bothers you
>>> bm = getattr(a, d.pop("action"))
>>> bm(**d)
calling first
x = 1
a = None
>>> d["a"] = 99
>>> bm(**d)
calling first
x = 1
a = 99
Peter
More information about the Python-list
mailing list