Why don't optional mutable objects show up in vars(func)?
Georg Brandl
g.brandl-nospam at gmx.net
Wed Sep 27 12:41:09 EDT 2006
dannycolligan at gmail.com wrote:
> So I just got bitten by the "don't use a mutable object as an optional
> argument" gotcha. I now realize that for this function:
>
>>>> def func(x, y=[]):
> ... y.append(x)
> ... print y
> ...
>
> y is initialized when the function is imported, not when the function
> is executed. However, if this is the case, then why is y not showing
> up as an attribute of func?
>
>>>> vars(func)
> {}
>>>> dir(func)
> ['__call__', '__class__', '__delattr__', '__dict__', '__doc__',
> '__get__', '__getattribute__', '__hash__', '__init__', '__module__',
> '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
> '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults',
> 'func_dict', 'func_doc', 'func_globals', 'func_name']
>
> I'm using Python 2.4.3, if that is at all relevant. Thanks in advance
> for any help.
y is not an attribute of func, it's a default parameter value and as such
stored in func_defaults:
>>> def f(x=1):
... pass
...
>>> print f.func_defaults
(1,)
>>>
Georg
More information about the Python-list
mailing list