Run time default arguments

Stephen Hansen me+list/python at
Sat Aug 27 20:48:03 CEST 2011

On 8/25/11 1:54 PM, ting at wrote:
> On Aug 25, 10:35 am, Arnaud Delobelle <arno... at> wrote:
>> You're close to the usual idiom:
>> def doSomething(debug=None):
>>     if debug is None:
>>         debug = defaults['debug']
>>     ...
>> Note the use of 'is' rather than '=='
>> HTH
> Hmm, from what you are saying, it seems like there's no elegant way to
> handle run time defaults for function arguments,

Well, elegance is in the eye of the beholder: and the above idiom is
generally considered elegant in Python, more or less. (The global nature
of 'defaults' being a question)

> meaning that I should
> probably write a sql-esc coalesce function to keep my code cleaner. I
> take it that most people who run into this situation do this?
> def coalesce(*args):
>   for a in args:
>     if a is not None:
>       return a
>   return None
> def doSomething(debug=None):
>   debug = coalesce(debug,defaults['debug'])
>   # blah blah blah

Er, I'd say that most people don't do that, no. I'd guess that most do
something more along the lines of "if debug is None: debug = default" as
Arnaud said. Its very common Pythonic code.

In fact, I'm not quite sure what you think you're getting out of that
coalesce function. "Return the first argument that is not None, or
return None"? That's a kind of odd thing to do, I think. In Python at

Why not just:

    debug = defaults.get("debug", None)

(Strictly speaking, providing None to get is not needed, but I always
feel odd leaving it off.)

That's generally how I spell it when I need to do run time defaults.


   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog:

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 487 bytes
Desc: OpenPGP digital signature
URL: <>

More information about the Python-list mailing list