what does this do? (really basic question)

Daniel Yoo dyoo at hkn.eecs.berkeley.edu
Fri Mar 1 01:51:39 EST 2002


Dave Marotti <landshark at verticaladdiction.net> 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 **) ?


"kw" stands for "keyword", and what's being used is called a "keyword
argument".  Keyword arguments allow us to pass parameters to a
function in a very general way.  In the example above, the keyword
argument becomes a dictionary that captures any keyword variables that
"fall through the cracks" of a function call.

Keyword arguments aren't particular to class methods --- they're a
general concept in function calls.  Here's an example:

###
>>> def test_keywords(var1, var2, **keywords):
...     print 'var1 = ', var1
...     print 'var2 = ', var2
...     print 'keywords = ', keywords
... 
>>> test_keywords(3, 4)
var1 =  3
var2 =  4
keywords =  {}
>>> test_keywords(var2=4, var1=42)
var1 =  42
var2 =  4
keywords =  {}
>>> test_keywords(var2=4, var1=42, var3 =17, var4='planet')
var1 =  42
var2 =  4
keywords =  {'var4': 'planet', 'var3': 17}
>>> 
###

Here, the last call of test_keywords() shows that 'keywords' grabs all
all the variables unaccounted for.


Keyword arguments might seem somewhat Useless at a first glance, but
they are actually quite nice: Peter Norvig uses examples of keyword
arguments in his "Infrequently Asked Questions" page:

    http://norvig.com/python-iaq.html


There's also a little bit of explanation about them in the Python tutorial:

    http://www.python.org/doc/current/tut/node6.html#SECTION006720000000000000000


Please feel free to ask more questions about them.  Good luck to you!



More information about the Python-list mailing list