Mutable default values for function parameters

Brian Quinlan BrianQ at
Thu Oct 4 23:53:24 CEST 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
> won't work at all, because (d is None) evaluates to 1, which would
> used instead of the default value! Same goes for (d == None) I'm
> 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...


More information about the Python-list mailing list