keyword arguments and **

John Hunter jdhunter at ace.bsd.uchicago.edu
Fri Nov 15 10:31:11 EST 2002


>>>>> "Boudewijn" == Boudewijn Rempt <boud at valdyas.org> writes:

    Boudewijn> I feel right silly, but for the life of I don't
    Boudewijn> understand why the variables I pass to f as named
    Boudewijn> arguments stay remembered:

    >>>> def f(fields={}, **args):

The problem is with fields={}.  This is a famous problem that catches
everybody at least once that is caused by using use a mutable type as
the default value for a keyword argument.  A mutable type is one that
can be changed (list, dict) and an immutable one is one that cannot
(int, string, tuple, ...).

To avoid the problem you are seeing, you need to initialize fields
within the function itself.  The standard idiom is:

def f(fields=None, **args):
    if fields is None: fields = {}
    print fields
    fields.update(args)
    print "XXX", fields
 
f(a=1)
f(b=1)

For a little more information, take a look at this thread on
google groups

http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&threadm=mailman.1037195388.11008.python-list%40python.org&rnum=2&prev=/groups%3Fas_q%3Dpitfall%26safe%3Doff%26ie%3DUTF-8%26oe%3DUTF-8%26as_ugroup%3D*python*%26lr%3D%26num%3D30%26as_scoring%3Dd%26hl%3Den

John Hunter




More information about the Python-list mailing list