newbie: prefix operator "**"

James Henderson james at logicalprogression.net
Wed Jan 21 11:15:09 EST 2004


On Wednesday 21 January 2004 3:59 pm, Jeff Epler wrote:
> On Wed, Jan 21, 2004 at 10:33:49AM -0500, Christian Jauvin wrote:
> > Hello,
> >
> > I am playing with some classes in the Tkinter module
> > to learn some GUI basics.
>
> Take a look at the Tutorial, section 4.7.2.  The ** prefix for an
> argument means that it accepts arbitrary keyword arguments.
> http://python.org/doc/tut/node6.html#SECTION006720000000000000000
>
> Example:
>
> def f(**kw):
>     print kw
>
> >>> f(a=1, b=2)
>
> {'a': 1, 'b': 2}

Since Jeff beat me to it with his reply and reference to the tutorial I'll 
just add that ** is also used in a sort of reverse sense when calling - as 
opposed to defining - a function, so that you can pass a dictionary to a 
function and have all the key-value pairs treated as keyword arguments.  This 
is called the extended call syntax and might be useful, for example, if a 
function with keyword arguments dictionary wants to pass these values on to 
another function, e.g.:

def f(**kw):
    print kw

def g(**kw):
    f(**kw)  # extended call sytax

g(a=1, b=2)

With the same result as above.  Extended call sytax is most useful to avoid 
the use of the deprecated apply().  See:

http://www.python.org/doc/current/lib/non-essential-built-in-funcs.html

under apply()

and:

http://www.python.org/doc/current/ref/calls.html

Finally, as two stars are used for arbitrary dictionaries single stars are 
used for arbitrary sequences.

James
-- 
James Henderson, Logical Progression Ltd.
http://www.logicalprogression.net/
http://sourceforge.net/projects/mailmanager/





More information about the Python-list mailing list