where dos the default agument live in? local name spaces or gloabal namespaces or else?

Jeremy Hylton jeremy at alum.mit.edu
Sun Aug 18 18:30:44 CEST 2002

Neal Norwitz <neal at metaslash.com> wrote in message news:<pan.2002. at metaslash.com>...
> >>>def f(a, L=[]):
>        L.append(a)
>        return L
> The list L "lives" in the function.  It is instatiated
> once, at compile time.  This code has the side effect
> that L is updated with each call to f.  This can be
> useful for a cache, but generally it is a bug.

A slight correction: The list L is stored in the func_defaults member
of the function f.  The list is created when the def statement is
executed not at compile-time.  In most cases, this happens when a
module is loaded.  But if you have a nested function, a new list is
created every time the outer function is called.  The example below
demonstrates that a new list is created each time f() is called.

>>> def f():
...     def g(L=[]):
...             return id(L)
...     return g
>>> f()()
>>> f()()
>>> f()()

As far as the compiler is concerned, L is just a formal parameter.  


More information about the Python-list mailing list