**kw,**args what are these things ?

Nuff Said nuffsaid at phreaker.net
Wed Feb 4 08:51:40 EST 2004


On Wed, 04 Feb 2004 10:59:13 +0100, fowlertrainer wrote:

> I see these things in many sources, under wxPy:
> 
> def __init__(self,params,**kw,**args)
> 
> What are these parameters, and what's the meaning of the double * ?

Python functions can have positional arguments and keyword arguments;
if the *last* argument of a function begins with **, all extra keyword
arguments (i.e. those which do not match any of the parameter names of
the function) are put in a dictionary.

(The single * is used for passing a variable number of arguments.)

You will thus often see function definitions like the following:

    def f(x, y, *args, **kw):
	# the dictionary is kw

The following example should make this a little bit clearer:

    def f(x, y, *args, **kw):
        print x, y,
    
        for i in args:
            print i,
        
        for k, v in kw.iteritems():
            print k, v,
        
    f(1, 2, 3, 4, five=5, six=6)

The output of this example is: 

    1 2 3 4 six 6 five 5

(Observe that dictionaries are not sorted!)

Remark: in your example, the ** is used two times; that is not
allowed (and does not make sense).

HTH / Nuff




More information about the Python-list mailing list