Keyword arguments - strange behaviour?

Fuzzyman fuzzyman at gmail.com
Thu Dec 23 06:45:26 EST 2004


brian.b... at securetrading.com wrote:
> > Channelling the effbot, I think he was asking what namespace
context
> you
> > expected the expression "arg=otherfunction(x)" to be evaluated in
> when
> > it's used at the time of a function call to dynamically create a
new
> > default value for arg.
>
> Thanks, I realise now that's what was meant. I think I was just
> assuming otherfunction() would be globally available - but that's not
> something I want to go into since I can see now there will be
problems
> trying to define what python should do if it evaluated defaults at
the
> function call :)
>
> I think I can now explain to someone why there are good reasons that
> 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?
>
> Brian

One way that is *slightly neater* is to simply collect all keyword
arguments as a dictionary. Then compare with a dictionary of defaults
for any missing keywords.

def afunction(**keywargs):
defaults = {'param1' : [], 'param2' : {}, 'param3' : []}
for entry in defaults:
if not keywargs.has_key(entry):
keywargs[entry] = defaults[entry]

This keeps all your defaults in a single dictionary and avoids a really
long function definition.
Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml




More information about the Python-list mailing list