newbie: prefix operator "**"

C

Christian Jauvin

Hello,

I am playing with some classes in the Tkinter module
to learn some GUI basics.

One problem is that I can't figure what is the meaning
of the prefix operator "**". I'm guessing that it has
something to do with dictionnaries, but I can't find
any explanation of it in the Python doc, nor on Google.

Here is a code snipped which I would like to understand:

class AnyWidget:

def __init__(self, master=None, cnf=None, **kw):
if cnf is None:
cnf = {}
if kw:
cnf = _cnfmerge((cnf, kw))
fcnf = {}

Thanks!
 
J

Jeff Epler

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
{'a': 1, 'b': 2}

Tkinter uses this to pass the keyword arguments along to the next level,
eventually to the Tk command to create or configure a widget.

Jeff
 
J

James Henderson

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


{'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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

tkinter errors out without clear message 0
Tk 0
How to read image data into Tkinter Canvas? 0
IDLE stopped working 0
tkinter wm_delete_window 1
Tkinter(2) 2
bitmap problem 1
Python Tkinter Newbie question 2

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top