How to call a function using apply with keyword args?

Sylvain Thenault thenault at nerim.net
Thu Jun 13 05:27:37 EDT 2002


Anoop P B <anoop79 at myrealbox.com> writes:

> hi Achim,
> 
> try this:
> 
> def MyFkt(A=0,B=0,C=0): pass
> params = {'A':5,'B':8,'C':9}
> MyFkt(params)
> 
> the reason behind the error is coz u can only pass a dictionary using
> 'apply' for keyword arguments. and keyword args are of the form
> keyword=value (see docs)

I don't think this give the desired result:

>>> def MyFkt(A=0,B=0,C=0):     
...     print 'A=',A
...     print 'B=',B
...     print 'C=', C
... 
>>> MyFkt(params)
A= {'B': 8, 'C': 9, 'A': 5}
B= 0
C= 0

Actually, you have to tell that your dictionnary is the param list and not the
value of the first param:


>>> MyFkt(**params)
A= 5
B= 8
C= 9
>>> apply(MyFkt, [], params)
A= 5
B= 8
C= 9


> Achim Domma wrote:
> > Hi,
> > I have a function like this:
> > def MyFkt(A,B,C): pass
> > and some parameters from a config file:
> > params = {'A':5,'B':8,'C':9}
> > how can I call MyFkt with this parameters? I tried
> > apply(MyFkt,[],params)
> > but get this error:
> > TypeError: MyFkt() takes exactly 3 non-keyword arguments (0 given)
> > any idea?
> > greetings
> > Achim

-- 
Sylvain Thénault 



More information about the Python-list mailing list