Mutable default values for function parameters

Brian Quinlan BrianQ at ActiveState.com
Thu Oct 4 14:58:27 EDT 2001


> I've used this idiom myself many times. I eventuallu decided
> it was shorter
> as
>
> def sample(x, d = None):
>     d = d or []
>     d.append(x)
>     print d
>
> but this looks so weird I'd appreciate confirmation that it's a
valid
> replacement.

It is not a valid replacement because d can evaluate to zero for
values other than None e.g.

sample(x, '')
sample(x, 0)

Those should raise some sort of exception, not silently do the
default.

You could change it to:
d = (d is None) or []






More information about the Python-list mailing list