[Python-bugs-list] [ python-Bugs-448911 ] Empty list as default argument problem
noreply@sourceforge.net
noreply@sourceforge.net
Tue, 07 Aug 2001 13:59:32 -0700
Bugs item #448911, was opened at 2001-08-07 13:59
You can respond by visiting:
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=448911&group_id=5470
Category: Parser/Compiler
Group: None
Status: Open
Resolution: None
Priority: 5
Submitted By: Nobody/Anonymous (nobody)
Assigned to: Nobody/Anonymous (nobody)
Summary: Empty list as default argument problem
Initial Comment:
To begin, a test case (hopefully mozilla will preserve
the formatting..):
class node:
def __init__(self, attrs = []):
self.attrs = attrs
a = node()
b = node()
a.attrs.append("foo")
print b.attrs
This prints ["foo"], where one would expect it to print
[]. Rewriting node.__init__ as follows does the right
thing:
def __init__(self, attrs = []):
if not attrs:
self.attrs = []
else:
self.attrs = attrs
It appears that Python allocates the default empty list
argument once and reuses it across multiple
instantiations of the object, so that a and b share
the attrs variable. This is unexpected.
I've tested this on multiple platforms (Linux and IRIX)
and multiple versions of Python (1.5.2 and 2.1.1).
----------------------------------------------------------------------
You can respond by visiting:
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=448911&group_id=5470