newbie: prefix operator "**"

Aloysio Figueiredo xpythonist at yahoo.com.br
Thu Jan 22 04:50:46 EST 2004


The ** operator is also useful when you have a
dictionary and want to unpack it to pass as keyword
arguments to a function:

>>> def f(a,b):
...   print a, b
...
>>> f(1,'foo')
1 foo
>>> f(a=1, b='foo')
1 foo
>>> d = {'a':1, 'b':'foo'}
>>> f(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: f() takes exactly 2 arguments (1 given)
>>> f(**d)
1 foo
>>>

Aloysio

 --- James Henderson <james at logicalprogression.net>
escreveu: > 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/
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list 

______________________________________________________________________

Yahoo! GeoCities: a maneira mais fácil de criar seu web site grátis!
http://br.geocities.yahoo.com/




More information about the Python-list mailing list