Aaron has posted 3 posts at DZone. View Full User Profile

My Number 1 Java to Python Gotcha

08.18.2008
| 5617 views |
  • submit to reddit
Fredrik Lundh is almost certainly a benevolent alien in disguise, sent to Earth to help the pitiful human race drag itself up out of the muck.

In a recent post, he touched on something that burned me BAD when I first started slinging pythion: using mutables as default parameters.

My particular run-in was a cousin of what Fredik describes, using a mutable as a default class attribute. I had a class like this:

class MyPage(object):
errors = []
def __init__(self):
# set me up

def run(self):
try:
self.build_page()
except:
self.errors.append("Oops. Something went wrong")
My problem was that I was setting a mutable as a default attribute value. This meant that each instance of MyPage was sharing the same error list; analagous to a static class variable in Java. It wasn't long before everything had errors, since the array just kept growing. This happened in a production environment. Sub-awesome indeed. What I SHOULD have done is this:

class MyPage(object):
errors = None
def __init__(self):
# set me up
self.errors = []

def run(self):
try:
self.build_page()
except:
self.errors.append("Oops. Something went wrong")

The __init__ clears out the array each time a new object is created. No sharing between instances. No pain.
References
Published at DZone with permission of its author, Aaron Oliver. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Jack Jackson replied on Mon, 2011/03/28 - 8:35am

Actually, that's wrong. You shouldn't declare instance variables that way. Just delete the errors = [] line and everything will work as expected.

 

 >>> class A(object):
... v = "Class variable"
... def __init__(self):
... self.v = "Instance variable"
...
>>> print A.v
Class variable
>>> h = A()
>>> print h.v
Instance variable
>>> print A.v
Class variable 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.