[ python-Bugs-1427789 ] List not initialized if used as default argument

SourceForge.net noreply at sourceforge.net
Wed Feb 8 20:13:39 CET 2006


Bugs item #1427789, was opened at 2006-02-08 19:55
Message generated for change (Comment added) made by birkenfeld
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1427789&group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Interpreter Core
Group: Python 2.4
Status: Closed
>Resolution: Invalid
Priority: 5
Submitted By: Jason (griminventions)
Assigned to: Nobody/Anonymous (nobody)
Summary: List not initialized if used as default argument

Initial Comment:
class A( object ):
    def __init__( self, someList = [] ):
        self.someList = someList

if __name__ == "__main__":
    for i in range( 10 ):
        a = A()
        a.someList.append( "abc" )
        print a.someList

Instead of each instance of A getting an empty list, it
is somehow the same list as the previous instance of A.
It will not occur with the following change:

class A( object ):
    def __init__( self ):
        self.someList = []

I'm using Windows XP, Python 2.4.1.
jason at griminventions.com


----------------------------------------------------------------------

>Comment By: Georg Brandl (birkenfeld)
Date: 2006-02-08 20:13

Message:
Logged In: YES 
user_id=1188172

This is intended behavior. Default values for function
arguments are only evaluated once, so it's not advisable to
use mutables there.

Use None as default and create your empty list within the
constructor if None is given, as in your second example.

----------------------------------------------------------------------

Comment By: Georg Brandl (birkenfeld)
Date: 2006-02-08 20:13

Message:
Logged In: YES 
user_id=1188172

This is intended behavior. Default values for function
arguments are only evaluated once, so it's not advisable to
use mutables there.

Use None as default and create your empty list within the
constructor if None is given, as in your second example.

----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1427789&group_id=5470


More information about the Python-bugs-list mailing list