keyword arguments and **

Alex Martelli aleax at aleax.it
Fri Nov 15 10:09:16 EST 2002


Boudewijn Rempt wrote:

> I feel right silly, but for the life of I don't understand why
> the variables I pass to f as named arguments stay remembered:
> 
>>>> def f(fields={}, **args):
> ...     print fields
> ...     fields.update(args)
> ...     print "XXX", fields
> ...
>>>> f(a=1)
> {}
> XXX {'a': 1}
>>>> f(a=1)
> {'a': 1}
> XXX {'a': 1}
>>>> f(b=1)
> {'a': 1}
> XXX {'a': 1, 'b': 1}
>>>> 

Usual problem: when an argument (here, fields) has a default
value that is mutable, that value is determined ONCE, when the
def statement executes -- then that single value stays around
(the function object references it), and if you mutate it you
get such a "memory effect".

Usual fix:

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


Alex




More information about the Python-list mailing list