Mutable default values for function parameters

John Roth johnroth at
Fri Oct 5 00:20:52 CEST 2001

"Brian Quinlan" <BrianQ at> wrote in message
news:mailman.1002222005.17547.python-list at
> > 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.

Actually, it is valid, within what we normally expect for validity.
Why? The very next statement is "d.append(x)", which is only
valid for lists or objects that export the proper methods for a
mutable sequence.

All the cases you mention are not mutable sequences, hence
they are invalid input to the function. If we wanted
to guard against invalid input, we should put in an assert statement,
rather than simply letting the append fail.

On the other hand, it will cause some otherwise invalid cases
to succeed.

John Roth

More information about the Python-list mailing list