[Python-bugs-list] [ python-Bugs-448911 ] Empty list as default argument problem

noreply@sourceforge.net noreply@sourceforge.net
Tue, 07 Aug 2001 14:07:41 -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: Python Interpreter Core
>Group: Not a Bug
>Status: Closed
>Resolution: Invalid
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).

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

>Comment By: Tim Peters (tim_one)
Date: 2001-08-07 14:07

Message:
Logged In: YES 
user_id=31435

Not a bug, functioning as designed.

See the FAQ entry

<http://www.python.org/cgi-bin/faqw.py?
req=show&file=faq06.025.htp>

for pointers to more discussion.

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

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