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

Neal Norwitz neal at metaslash.com
Thu Aug 15 23:49:52 EDT 2002


On Thu, 15 Aug 2002 23:17:53 -0400, lion wrote:

> I just feel name spaces are ambiguous in a sense.If I defined a
> function in the Python shell:

It's not ambiguous at all.

>>>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.

> and I invoked it with the default agrument value: f(1).Now I don't
> know where the default agument L lives in? No matter I use dir() or
> dir(f),there is no L listed in the result.


>>> def f(a, L=[]): pass
... 
>>> print f.func_code.co_varnames, f.func_defaults
('a', 'L') ([],)

Note the defaults work from last parameter to the first.
But you need to evaluate from the end of the tuple.

>>> def f(a=1, L=[]): pass
... 
>>> print f.func_code.co_varnames, f.func_defaults
('a', 'L') (1, [])


Neal



More information about the Python-list mailing list