Keyword arguments - strange behaviour?
Alex Martelli
aleaxit at yahoo.com
Fri Dec 24 03:46:04 EST 2004
<brian.bird at securetrading.com> wrote:
...
> the default params are evaluated at the definition. However, I still
> can't give a nice looking solution on how to re-write a function to
> have empty mutable values as default arguments: eg.
>
> def method(a,b,opt1=[],opt2=None,opt3="",opt4={})
>
> How could I re-write this (especially if there are perhaps 20 optional
> parameters,any number of which may have mutable defaults) without
> writing 20 "if opt1 is None: opt1=[]" statements?
I don't have the recipe I mentioned at hand, but what about:
def makebrianhappy(f):
saved_defaults = f.func_defaults
def with_fresh_defaults(*a, **k):
f.func_defaults = copy.deepcopy(saved_defaults)
return f(*a, **k)
with_fresh_defaults.__name__ = f.__name__
return with_fresh_defaults
@ makebrianhappy
def method(a, b, opt1=[], opt2=None, opt3="", opt4={}):
...
I've added spaces after commas to make ME happy too (lack of such spaces
is my least favourite Python irritation;-), but I guess the semantics of
this (UNTESTED) code would work even without that;-).
Alex
More information about the Python-list
mailing list