Strange Behavior

A

abcd

class Foo:
def __init__(self, name, data=[]):
self.name = name
self.data = data

def addData(self, val):
self.data.append(val)


f = Foo('a')
f.addData(1)
f.addData(2)

f2 = Foo('b')

print f.name, f.data
print f2.name, f2.data

----------------------------
OUTPUT
---------------------------
a [1, 2]
b [1, 2]


.....why would f and f2 contain the same data??

however, if I do this instead....

f = Foo('a')
f.addData(1)
f.addData(2)

f2 = Foo('b', [])

print f.name, f.data
print f2.name, f2.data

----------------------------
OUTPUT
---------------------------
a [1, 2]
b []


Any ideas? is this a bug?
 
S

Steven D'Aprano

class Foo:
def __init__(self, name, data=[]):

The binding of the name "data" to the empty list happens at compile time,
not runtime.
self.name = name
self.data = data

def addData(self, val):
self.data.append(val)

Every time you call addData on an instance, it appends to the same list.
So all instances created with Foo(name) share the same list in data.

Think of it like this:

some_list = []
x = Foo("fred", some_list)
y = Foo("wilma", some_list)

Isn't it obvious now that both instances share the same list? That x.data
and y.data don't just have the same value, but are the same object? The
same thing happens when you set the default.

f = Foo('a')
f.addData(1)
f.addData(2)

f2 = Foo('b', [])

And in this case, you've passed a DIFFERENT empty list as an argument.


The normal Python way for handling this situation is to not use mutable
objects as defaults unless you want this behaviour. Instead, use None as
the default value:

class Foo:
def __init__(self, name, data=None):
self.name = name
if data is None: self.data = []
else: self.data = data

Any ideas? is this a bug?

Well, it's a bug in your code :)

It isn't a bug in Python. At worst, it is a "gotcha", but it is a
deliberate design decision, and quite useful. For example, this is good
for caching complicated calculations:

def function(x, _cache={}):
# _cache is initialised to an empty dictionary at compile time
if _cache.has_key(x):
return _cache[x]
else:
# complicated and time consuming calculation happens
_cache[x] = result
return result
 
P

Paul Rubin

Steven D'Aprano said:
It isn't a bug in Python. At worst, it is a "gotcha", but it is a
deliberate design decision, and quite useful. For example, this is good
for caching complicated calculations:

def function(x, _cache={}):
# _cache is initialised to an empty dictionary at compile time
if _cache.has_key(x):
return _cache[x]

The above can be done explicitly:

def function(x):
if function._cache.has_key(x):
return function._cache[x]
...
# function gets an initially-empty cache
function._cache = {}

So the existing behavior, while not a bug (since it's documented), may
well be a wart.
 
N

Neil Cerutti

Well, it's a bug in your code :)

It isn't a bug in Python. At worst, it is a "gotcha", but it is
a deliberate design decision, and quite useful. For example,
this is good for caching complicated calculations:

I'd say the feature is "usable" rather than "useful", like
bitfields in C.
 
F

Fredrik Lundh

Steven said:
It isn't a bug in Python. At worst, it is a "gotcha", but it is a
deliberate design decision, and quite useful. For example, this is good
for caching complicated calculations:

it's also used to pass in *objects* instead of names into an inner scope.

</F>
 
D

Diez B. Roggisch

abcd said:
thanks. weird that it works that way since they even state "This is
generally not what was intended."

The "not intended" refers to the programmer making the mistake of creating a
shared instance - which usually isn't intended, as you yourself are an
example of.

Diez
 
C

Carsten Haese

class Foo:
def __init__(self, name, data=[]):

The binding of the name "data" to the empty list happens at compile time,
not runtime.

I think this statement needs to be clarified. The binding of "data" to
the empty list *does* happen at runtime, not at compile time. However,
the binding happens only once, when the "def" statement is executed, as
opposed to every time the __init__ function is called.

-Carsten
 
F

Fredrik Lundh

Carsten said:
I think this statement needs to be clarified. The binding of "data" to
the empty list *does* happen at runtime, not at compile time. However,
the binding happens only once, when the "def" statement is executed, as
opposed to every time the __init__ function is called.

to be precise, it happens every time the "def" statement is executed.

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top