Run time default arguments
MRAB
python at mrabarnett.plus.com
Thu Aug 25 10:50:24 EDT 2011
On 25/08/2011 15:30, ting at thsu.org wrote:
> What is the most common way to handle default function arguments that
> are set at run time, rather than at compile time? The snippet below is
> the current technique that I've been using, but it seems inelegant.
>
> defaults = { 'debug' : false }
> def doSomething (debug = None):
> debug = debug if debug != None else defaults['debug']
> # blah blah blah
>
> Basically, I want to define a set of common defaults at the module and/
> or class level but let them be overridden via function arguments. The
> simpler, naive approach does not work, because the argument gets set
> at compile time, rather than at run time. That is:
> def doSomething(debug = defaults['debug'])
> ends up being compiled into:
> def doSomething(debug = false)
> which is not the behavior I want, as I want to evaluate the argument
> at run time.
>
> Any better suggestions?
>
The recommended way is:
def doSomething (debug = None):
if debug is None:
debug = defaults['debug']
It's more lines, but clearer.
More information about the Python-list
mailing list