Mutable default values for function parameters
Steve Holden
sholden at holdenweb.com
Thu Oct 4 15:10:11 EDT 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
> 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 []
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.
regards
Steve
--
http://www.holdenweb.com/
More information about the Python-list
mailing list