472,347 Members | 2,085 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,347 software developers and data experts.

Strange Behavior

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?

Oct 16 '06 #1
9 1114
abcd wrote in news:11**********************@i3g2000cwc.googlegro ups.com in
comp.lang.python:
class Foo:
def __init__(self, name, data=[]):
http://docs.python.org/ref/function.html#l2h-619

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Oct 16 '06 #2
Rob Williscroft wrote:
http://docs.python.org/ref/function.html#l2h-619

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

oh well.

Oct 16 '06 #3
On Mon, 16 Oct 2006 07:26:05 -0700, abcd wrote:
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


--
Steven.

Oct 16 '06 #4
Steven D'Aprano <st***@REMOVE.THIS.cybersource.com.auwrites:
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.
Oct 16 '06 #5
On 2006-10-16, Steven D'Aprano
<st***@REMOVE.THIS.cybersource.com.auwrote:
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.

--
Neil Cerutti
Next Sunday Mrs. Vinson will be soloist for the morning service.
The pastor will then speak on "It's a Terrible Experience."
--Church Bulletin Blooper
Oct 16 '06 #6
Steven D'Aprano wrote:
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>

Oct 16 '06 #7
abcd wrote:
Rob Williscroft wrote:
>http://docs.python.org/ref/function.html#l2h-619


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
Oct 16 '06 #8
On Mon, 2006-10-16 at 10:51, Steven D'Aprano wrote:
On Mon, 16 Oct 2006 07:26:05 -0700, abcd wrote:
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
Oct 16 '06 #9
Carsten Haese wrote:
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>

Oct 16 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Marcus | last post by:
Hello, I recently converted all my existing MyISAM tables to InnoDB tables through phpmyadmin. I noticed some strange behavior whenever I would...
36
by: Dmitriy Iassenev | last post by:
hi, I found an interesting thing in operator behaviour in C++ : int i=1; printf("%d",i++ + i++); I think the value of the expression "i++ +...
0
by: thulsey | last post by:
Hi all, I've got some strange behavior happening in Firefox and Safari (Khtml and Gecko) that displays *almost* fine in IE6.0 (still trying to...
1
by: Alexander Inochkin | last post by:
Hi! I found same strange behavior of ASP.NET. It is possible this is the bug. Follow the steps:
0
by: ivb | last post by:
Hi all, I am using DB2 8.1.11.1 on NT with ASP.NET 1.1 When application make connection to database (via ADO.NET), it set "Connection timeout"...
6
by: Joseph Geretz | last post by:
Writing an Outlook AddIn with C#. For the user interface within Outlook I'm adding matching pairs of Toolbar buttons and Menu items. All of the...
3
by: sara | last post by:
Very strange behavior, but I suspect some is A2K and some might be for me to correct. Just trying to see if anyone can help and advise. We have...
1
by: Nicholas Palmer | last post by:
Hi all, Got a question about the AspCompat=true page property. First a little background. We have an ASP.NET app that uses two COM components....
19
by: david | last post by:
I took old code and decided to modify it a bit, and I just noticed that it does not compile at all and before server one of severs (main) crashed...
20
by: Pilcrow | last post by:
This behavior seems very strange to me, but I imagine that someone will be able to 'explain' it in terms of the famous C standard. ...
0
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.