Empty list as default parameter

Fredrik Lundh fredrik at pythonware.com
Fri Nov 21 07:36:50 EST 2003


Alex Panayotopoulos wrote:

> 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?

the default value expression is evaluated once, when the function
object is created, and the resulting object is bound to the argument.

if you want to create a new object on every call, you have to do
that yourself:

    def __init__( self, myList=None):
        if myList is None:
            myList = [] # create a new list
        self.myList = myList

or perhaps:

    def __init__( self, myList=None):
        self.myList = myList or []

see the description of the "def" statement for more info:

    http://www.python.org/doc/current/ref/function.html

</F>








More information about the Python-list mailing list