Empty list as default parameter
anton muhin
antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Fri Nov 21 07:42:14 EST 2003
Alex Panayotopoulos wrote:
> Hello all,
>
> Maybe I'm being foolish, but I just don't understand why the following
> code behaves as it does:
>
> - = - = - = -
>
> class listHolder:
> def __init__( self, myList=[] ):
> self.myList = myList
>
> def __repr__( self ): return str( self.myList )
>
> # debug: 'a' should contain 42, 'b' should be empty. But no.
> a = listHolder()
> a.myList.append( 42 )
> b = listHolder()
> print a
> print b
>
> - = - = - = -
>
> I was expecting to see [42] then [], but instead I see [42] then [42]. It
> seems that a and b share a reference to the same list object. Why?
>
Really common mistake: lists are _mutable_ objects and self.myList
references the same object as the default parameter. Therefore
a.myList.append modifies default value as well. Mutable defaults are
better avoided (except for some variants of memo pattern). Standard
trick is:
def __init__(self, myList = None):
if myList is None:
self.myList = []
else:
self.myList = myList
regards,
anton.
More information about the Python-list
mailing list