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 12:30:44 EDT 2002
Neal Norwitz <neal at metaslash.com> wrote in message news:<pan.2002.08.16.03.49.46.535623.6701 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()()
1075264572
>>> f()()
1075262612
>>> f()()
1075263228
As far as the compiler is concerned, L is just a formal parameter.
Jeremy
More information about the Python-list
mailing list