Function __defaults__
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun Apr 24 22:00:53 EDT 2011
On Sun, 24 Apr 2011 10:07:02 -0700, Ken Seehart wrote:
> On 4/24/2011 2:58 AM, Steven D'Aprano wrote:
[...]
>> 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
Thanks to everyone who replied. Obviously my google-foo was weak
yesterday, because I did search for an answer.
However, __getitem__ appears to be ignored when looking up defaults:
>>> class Magic(tuple):
... def __getitem__(self, i):
... print("magic!")
... return super().__getitem__(i)
...
>>> def f(a, b=2):
... return a+b
...
>>> f.__defaults__ = Magic(f.__defaults__)
>>> f.__defaults__[0]
magic!
2
>>> f(40)
42
Which is a pity, because I had an awesome idea for a hack to "fix" the
mutable default function argument gotcha with a decorator, but
unfortunately it relies on __getitem__ being called.
def fixed_default(func):
class Magic(tuple):
def __getitem__(self, i):
x = super().__getitem__(i)
if x == []:
return list()
return x
func.__defaults__ = Magic(func.__defaults__)
return func
--
Steven
More information about the Python-list
mailing list