initializing with empty list as default causes freaky problems

Gary Herron gherron at islandtraining.com
Tue Jul 28 01:06:36 CEST 2009


Reckoner wrote:
> Hi,
>
> Observe the following:
>
> In [202]: class Foo():
>    .....:     def __init__(self,h=[]):
>    .....:         self.h=h
>    .....:
>    .....:
>
> In [203]: f=Foo()
>
> In [204]: g=Foo()
>
> In [205]: g.h
> Out[205]: []
>
> In [206]: f.h
> Out[206]: []
>
> In [207]: f.h.append(10)
>
> In [208]: f.h
> Out[208]: [10]
>
> In [209]: g.h
> Out[209]: [10]
>
> The question is: why is g.h updated when I append to f.h?  Shouldn't
> g.h stay []?
>
> What am I missing here?
>
> I'm using Python 2.5.1.
>
> Thanks in advance.
>   

This is a FAQ (and *very* common newbie trap)!  See:

  
http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects

Gary Herron




More information about the Python-list mailing list