Mutable default values for function parameters
johnroth at ameritech.net
Fri Oct 5 00:20:52 CEST 2001
"Brian Quinlan" <BrianQ at ActiveState.com> wrote in message
news:mailman.1002222005.17547.python-list at python.org...
> > 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
> > 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
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
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
More information about the Python-list