[Tutor] arguements

Jason Stokes jstok@bluedog.apana.org.au
Thu, 28 Sep 2000 13:58:36 +1100


Suzanne Little wrote:
> 
> Hello,
> 
> Would someone be able to explain to me (or point me to an
> explanation) what the * and ** mean? These occur in the argument list to
> some methods I've been reading in Tkinter. For example the keyword
> dictionary **kw. What is included in this dictionary and how does it
> work? How can I access it or use it? Why, when I pass it to another method
> in the init method do I need to do it as just kw? I've also seen the *
> used in things like *args. How does this work? And what does it do?

The * character in a function signature indicates that function accepts
a variable number of positional arguments.  The arguments are provided
at a call site thusly:

foo(a, b, optional1, optional2, ...)

But actually passed to the function as a tuple referred to by the name
given in the signature -- in this case, "args".

The ** declarer means the same thing, but this time referring to a
variable number of keyword arguments of the form:

foo(a, b, option1 = q, option2 = p)

These are passed as pairs in a dictionary referred to by the name given
in the signature -- in this case, kw.

If these two declarers are used together in a function, that means it
accepts a variable number of positional arguments and a variable number
of keyword arguments. The syntax for this is clear if you always put the
positional arguments first and the keyword arguments second.

The main use of the variable-sized keyword arguments in the Tkinter
module is to provide support for the extensive use of variable numbers
of keyword arguments used within Tk/TCL itself.  

* has no relationship at all with the C pointer dereferencing operator
that uses the same Ascii symbol.

The reason you need to pass kw to another method called from init is
simply because it's not a special datatype, simply a dictionary with the
special property that, before the call is executed, the interpreter
examines the keyword arguments, takes ones that don't match any of the
formal paramaters, and inserts them in the dictionary so you can get
access to them.  You'd have no way of accessing those variables
otherwise.

Cheers,
Jason Stokes: jstok@bluedog.apana.org.au