Mutable default values for function parameters

Brian Quinlan BrianQ at ActiveState.com
Thu Oct 4 17:53:24 EDT 2001


> > You could change it to:
> > d = (d is None) or []
>
> Tanks, I remember finding the particular fly you metnion in
> the ointment. I could conveniently ignore it for my needs, however,
> as all non-default values were also non-false. However, your
solution
> won't work at all, because (d is None) evaluates to 1, which would
be
> used instead of the default value! Same goes for (d == None) I'm
afraid.
>
> Things are never as easy as they seem.

It's not like I test my code before I recommend it to other people or
anything :-) But this time I'll make an exception:

Here is my proposed expression:

d = ((d is not None and [d]) or [[]])[0]

Here is the test:

def test(d = None):
    return ((d is not None and [d]) or [[]])[0]

assert test() == []
assert test(None) == []
assert test(0) == 0
assert test('') == ''
assert test(5) == 5
assert test([1,2,3]) == [1,2,3]

I believe that those are the semantics that you are looking for? And
so easy to understand...

Cheers,
Brian





More information about the Python-list mailing list