[Python-ideas] my take on mutable default arguments
tomer filiba
tomerfiliba at gmail.com
Sat Jan 27 22:30:51 CET 2007
i thought this code be solved nicely with a decorator... it needs some
more work, but it would make a good cookbook recipe:
.>>> from copy import deepcopy.
.>>>
.>>> def defaults(**kwdefs):
... def deco(func):
... def wrapper(*args, **kwargs):
... for k,v in kwdefs.iteritems():
... if k not in kwargs:
... kwargs[k] = deepcopy(v)
... return func(*args, **kwargs)
... return wrapper
... return deco
...
.>>> @defaults(x = [])
... def foo(a, x):
... x.append(a)
... print x
...
.>>> foo(5)
[5]
.>>> foo(5)
[5]
.>>> foo(5)
[5]
maybe it should be done by copying func_defaults... then it could
be written as
@copydefaults
def f(a, b = 5, c = []):
...
-tomer
More information about the Python-ideas
mailing list