Mutable default values for function parameters

Steve Holden sholden at holdenweb.com
Thu Oct 4 14:31:52 EDT 2001


"Erik Max Francis" <max at alcyone.com> wrote in message
news:3BBCA084.B10B6061 at alcyone.com...
> sebastien wrote:
>
> > I'd like to point something that is said in §4.7.1 of the tutorial:
> >
> > "Important warning: The default value is evaluated only once. This
> > makes a difference when the default is a mutable object such as a list
> > or dictionary"
> >
> > I think that this point is really difficult to understand. That means
> > that parameters with mutable default value are global to all the calls
> > of the function:
> ...
> >
> > This is a really confusing and I always fall in this sort of trap.
> > Maybe a bad neuronal connection;-)
>
> I avoid this problem by simply never using a mutable object as a default
> argument, but instead always using a sentinel value that's substituted
> in the function body:
>
> def sample(x, d = None):
>     if d is None:
>         d = []
>     d.append(x)
>     print d
>
> To be honest, I can't remember ever running into this pitfall, since
> I've used this pattern ever since I started using Python, and happened
> to be made aware of the rule before encountering the wrong end of it.
>
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.

tormented-by-self-doubt-ly y'rs -  steve
--
http://www.holdenweb.com/







More information about the Python-list mailing list