Function __defaults__

Ken Seehart ken at seehart.com
Mon Apr 25 08:30:34 EDT 2011


On 4/25/2011 4:59 AM, Colin J. Williams wrote:
> 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.
>

I assume you mean making the value of f.__defaults__ a dictionary 
instead of a tuple.

A dictionary would be slower to process since it would have to iterate 
the dictionary keys and assign arguments by name.
Since argument defaults can only be applied to the rightmost contiguous 
sequence of zero or more parameters (excluding *args,**kwargs),  a tuple 
is sufficient to cover all cases, so a dictionary would provide no 
advantage.
Also, a dictionary would produce an unnecessary error case (if a key in 
the dictionary is not the name of an argument).

Good question though.

Cheers,
Ken




More information about the Python-list mailing list