*args and **kwargs
Andrew Lusk
alusk at uiuc.edu
Tue Nov 26 20:08:12 EST 2002
"Dan" <dan at cox.com> writes:
> I am still pretty new on Python and have been working with it for 5 months.
> I ran across some source code that has these constructs. They look like C
> pointers but most likely aren't. I can't find explanations to them in
> reference books but have only seen them on function declarations in the
> sources. Can anyone give a brief explanation or provide a pointer link to
> an explanation?
*args is for multiple arguments.
>>> def foo(*args):
... print args
...
>>> foo(1,2,3,4,5)
(1, 2, 3, 4, 5)
So it treats its arguments as a tuple.
**args is for keyword arguments.
>>> def foo2(**args):
... print args
...
>>> foo2(a=1,b=2,c=[])
{'a': 1, 'c': [], 'b': 2}
So you can send in keyval pairs and it will get a dictionary. Useful
for having multiple unordered optional arguments.
--Andrew
More information about the Python-list
mailing list