Passing parameters using **kargs
Duncan Booth
me at privacy.net
Tue Jun 8 04:21:46 EDT 2004
tkpmep at hotmail.com (Thomas Philips) wrote in
news:b4a8ffb6.0406071858.24dbb8ee at posting.google.com:
> I want to access parameters that are passed into a function using the
> **kargs idiom. I define f(**kargs) via
>
> def f(**kargs):
> print kargs
> .
> .
>
> the keyword arguments are converted to a dictionary, so that if I type
> f(a=1, b=2, c=3)
>
> the function prints
> {'a': 1, 'b': 2, 'c':3}
>
> Now assume the function has three variables a, b and c to which I want
> to assign the dictionary's values of 'a', 'b' and 'c'. How can I
> assign kargs['a'] to a, kargs['b'] to b, and kargs['c'] to c. Should I
> be trying to construct a string representation of each variable's name
> and using that as a key, or am I just thinking about this the wrong
> way?
>
If the function is to have three variables a, b, and c, then you do this:
def f(a=None, b=None, c=None, **kargs):
... whatever ...
(substitute whatever defaults you want for those variables)
The ** argument is for keyword arguments where you don't know in advance
all the keywords that might be valid. Obviously, if you don't know the name
in advance then there is no point to setting a variable of the same name
since you would have to go through pointless contortions to access it.
If you do know some names of interest in advance then make them arguments
with default values and only use the ** form for the remaining arguments.
More information about the Python-list
mailing list