Why don't optional mutable objects show up in vars(func)?
"Martin v. Löwis"
martin at v.loewis.de
Wed Sep 27 12:54:32 EDT 2006
dannycolligan at gmail.com schrieb:
> 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?
Because it's not an attribute of the function object; it's a default
value of the function.
>>>> 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.
Take a look at func_defaults.
Regards,
Martin
More information about the Python-list
mailing list