What's wrong?

Michael Hudson mwh21 at cam.ac.uk
Sun Oct 24 12:30:29 EDT 1999


Fuming Wang <fuming at venus.radsci.uci.edu> writes:

> Hi, following code snippet gave me a surpise. Could anyone tell me what's
> wrong?
> 
> >>> class A:
> ...     def __init__(self, list=[]):
> ...          self._list = list
> ... 
> >>> a = A()
> >>> a._list
> []
> >>> b = A()
> >>> b._list
> []
> >>> a == b
> 0
> >>> a is b 
> 0
> >>> a._list.append(4)
> >>> a._list
> [4]
> >>> b._list
> [4]
> >>> 

Oh God, this one again.

Your example is a little more complicated than it needs to be to
illustrate the behaviour that's troubling you.

consider:

>>> def f(a,b=[]):
...  b.append(a)
...  return b
...
>>> f(2)
[2]
>>> f("f")
[2, 'f']
>>> f(f)
[2, 'f', <function f at 8118dd8>]

the point is that default arguments are only evaluated once, at
"compile" time, i.e. when the def statement is evaluated.

To do what you want to do, write code like this:

class A:
    def __init__(self,l=None):
        if l is None:
             self._list = []
        else:
             self._list = l

`list' is probably a poor choice for a variable name as it shadows the
name of a builtin function.

don't-worry-everyone-gets-bitten-by-this-at-least-once-ly y'rs
Michael




More information about the Python-list mailing list