confused with local variables being retained

Tim Hochberg tim.hochberg at ieee.org
Tue Nov 21 14:24:26 EST 2000



> Dan Brown wrote:
> > I'm being confused (I guess) by namespace or scoping rules in Python; I
> > don't quite know why this piece of code is having the effect that it is:
> >
> > class simple:
> >     def __init__ (self, label = 'spam'):
> >         self.label = label;
> >
> >     def display (self, stufflist = []):
> >         stufflist.append (self.label)
> >         print stufflist
>
>     http://www.python.org/doc/FAQ.html#6.25
>     6.25. Why are default values sometimes shared between objects?
>
>     "Default values are created when the function is DEFINED,
>     that is, there is only one such object that all functions refer
>     to. If that object is changed, subsequent calls to the function
>     will refer to this changed object"


In practice this means that you should stay away from using mutable objects
(e.g., lists) as default arguments. Unless of course you understand their
effects and want to do something sick^H^H^H^H slick.

The common idiom for dealing with this case is:

     def display (self, stufflist=None):
        if stufflist is None:
            stufflist = []
        stufflist.append (self.label)
        print stufflist


-tim





More information about the Python-list mailing list