Function params with **? what do these mean?
Larry Bates
larry.bates at websafe.com
Mon Mar 20 16:16:20 EST 2006
J Rice wrote:
> I'm sorry for such a basic question, but I haven't been able to phrase
> a search that gets me an answer and my books are totally silent on
> this. I have seen a number of python function defs that take
> parameters of the form (**param1). Looks like a pointer... but my
> books on python (basic as they are) don't make a mention. What is
> this?
>
> Jeff
>
There are too forms that you may be confusing. First
>>> def foo(x,y,z):
>>> return x+y+z
>>> t=[1,2,3]
>>> foo(*t)
6
This tells python to expand t and pass it as as 3
separate arguments
The second is:
>>> def foo(*args):
>>> return sum(args)
>>> foo(1,2,3)
6
This allows you to treat all the arguments to a function
as a list of arguments no matter how many there are.
or
>>> def bar(**kwargs):
>>> for key, value in kwargs.items():
>>> print "key=%s, value=%s" % (key, value)
>>> return
>>> bar(a=1, b=2, c="this is a test")
key=a, value=1
key=c, value=this is a test
key=b, value=2
This allows you to access keyword arguments via a dictionary
in the function, instead of individually.
You can combine these to make very powerful functions/methods
that can handle different numbers of arguments and keyword
arguments.
def foo(*args, **kwargs):
...
Larry Bates
More information about the Python-list
mailing list