Function __defaults__

Colin J. Williams cjw at ncf.ca
Mon Apr 25 07:59:46 EDT 2011


On 24-Apr-11 13:07 PM, Ken Seehart wrote:
> On 4/24/2011 2:58 AM, Steven D'Aprano wrote:
>> Consider this in Python 3.1:
>>
>>
>>>>> def f(a=42):
>> ... return a
>> ...
>>>>> f()
>> 42
>>>>> f.__defaults__ = (23,)
>>>>> f()
>> 23
>>
>>
>> Is this an accident of implementation, or can I trust that changing
>> function defaults in this fashion is guaranteed to work?
>
> This is documented in python 3, so I would expect it to be stable (until
> python 4, that is)
> http://docs.python.org/py3k/whatsnew/3.0.html#operators-and-special-methods
> http://docs.python.org/py3k/library/inspect.html#types-and-members
>
> The f.__defaults__ attribute was previously known as f.func_defaults (in
> python 2.x), which has been around, documented and stable for quite a
> while.
>
> So it's probably just as safe as any other monkey patching technique. :)
>
> Best of luck,
> Ken
>

Wouldn't it make more sense to return a dictionary instead of a tuple?

Colin W.




More information about the Python-list mailing list