Why don't optional mutable objects show up in vars(func)?

dannycolligan at gmail.com dannycolligan at gmail.com
Wed Sep 27 18:32:46 CEST 2006


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.

Danny




More information about the Python-list mailing list