Python weirdness

Status
Not open for further replies.

extreme.boredom

Wise, Aged Ars Veteran
115
I'm working on a project for Uni and I need to do some of it in Python. I think I understand the basics, but I'm getting some behaviour that seems really strange to me. I have a class where multiple objects seem to share the same data and I have no idea why.

This is the relevant code from the class with the problem (I have verified this by typing the definition straight into the interpreter as well).

Code:
class SusitFrame:
	def __init__(self, type = None, length = -1, frameNum = -1, channel = None, content = []):
		self.type = type
		self.length = length
		self.frameNum = frameNum
		self.channel = channel
		self.content = content
	def addContent(self, newcontent):
		self.content.append(newcontent)

And this is what I get from the interpreter when I try and use the class.
Code:
>>> frame1 = susit.SusitFrame()
>>> frame2 = susit.SusitFrame()
>>> frame1.addContent('hello')
>>> frame1.content 
['hello']
>>> frame2.content
['hello']

And just for good measure - the output from the wholesale interpreter version.
Code:
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class SusitFrame:
...     def __init__(self, type = None, length = -1, frameNum = -1, channel = None, content = []):
...             self.type = type
...             self.length = length
...             self.frameNum = frameNum
...             self.channel = channel
...             self.content = content
...     def addContent(self, newcontent):
...             self.content.append(newcontent)
... 
>>> frame1 = SusitFrame()
>>> frame1
<__main__.SusitFrame instance at 0x1d5620>
>>> frame2 = SusitFrame()
>>> frame1.content
[]
>>> frame2.content
[]
>>> frame1.addContent('hello')
>>> frame1.content
['hello']
>>> frame2.content
['hello']
>>>

So, anyone have any ideas? What am I missing?

Thanks in advance.
 

extreme.boredom

Wise, Aged Ars Veteran
115
And now I've fixed it. It appears that the default value for content in the __init__ method persists across calls. So every time an object was constructed with the default value for content their self.content would end up pointing to the same list. Then modifying any one of them modified them in all objects. I fixed it by changing self.content = content to self.content = list(content).
 

norton_I

Ars Tribunus Angusticlavius
6,172
Subscriptor++
yeah. Default arguments are evaluated when the method is defined, it is generally advisable not to use mutable objects as default arguments.

Another standard way of dealing with this is:

Code:
def __init__(self, content=None):
    if content is None:
        content = []

The difference between the two is that if you pass a non-default argument to content it will be shared with the caller. Your solution always makes a copy of content, which is more likely what you want here.
 

karmakaze

Ars Tribunus Militum
1,700
Subscriptor
You might want to check out PyLint, it should help catch gotchas like that: http://www.logilab.org/857

if you want to keep your code a little more concise 'self.content = content or []' also works just like the if block on most fairly recent versions of Python (definitely 2.5+, not sure about 2.4-). Not a big deal with one default value, but if you have 5 or 6 all those if blocks get in the way of readability.
 

lostnihilist

Ars Scholae Palatinae
1,436
'self.content = content or []' also works just like the if block on most fairly recent versions of Python (definitely 2.5+, not sure about 2.4-).

That will definitely work on at least python2.3, probably any python2.X, though I don't have anything older than 2.3 around to test on. I think you are thinking of the ternary operator syntax:
Code:
self.content = content if content else []
which is unnecessary here. An alternative is to set content to an empty tuple and just do self.content = list(content), but that will produce a copy of your list, which may or may not be desirable.
 
Status
Not open for further replies.