what does this do? (really basic question)

Sean 'Shaleh' Perry shalehperry at attbi.com
Fri Mar 1 07:19:25 CET 2002

On 01-Mar-2002 Dave Marotti wrote:
> Hey,
> Hopefully this is a really basic question.  I'm still in the learning phase,
> and came across this in a sample program:
> class Whatever:
>     def __init__(self, user_list, cmd_list, **kw):
>         code....
> What does the **kw mean (specifically, the **) ?

the kw is a nmemonic for 'keyword'.

>>> def foo(**kw):
...   print kw
>>> foo(a=3, b=6, c='Sean')
{'b': 6, 'c': 'Sean', 'a': 3}
>>> foo(c='David', a=42, b=25)
{'b': 25, 'c': 'David', 'a': 42}

the ** syntax means 'take every argument that was not matches elsewhere and
store it in a dictionary.  The key will be the variable name and the value will
be its value'.

So self, use_list, and cmd_list will get their values and then kw gets the rest.

>>> def bar(name, **kw):
...   print name
...   print kw
>>> bar('Sean', a=1,b=2,c=3)
{'b': 2, 'c': 3, 'a': 1}
>>> def wuz(name, age):
...   print name
...   print age
>>> wuz(age=25, name='Lesley')

Note the key=value syntax works even without the **kw magic.

The advantage of using the key=value syntax is that it makes functions with
several arguments easier to call without reading the docs.  This is often handy
for things like GUI toolkits and network code:

win = MakeWindow(title="My Window", width=100, height=200, x=34, y=67)


socket = Network.Connect(url="http://www.python.org", keepalive=1, port=80)

More information about the Python-list mailing list