Class Variables versus Instance Variables in Python

While writing some Python, I ran into a behavior that I didn't expect. Check out the following chunk of code:

import unittest

class Task(object):
    keywords = []

class TestClass(unittest.TestCase):
    def test_keywords(self):
        mytask = Task()
        mytask.keywords.append("one")

        mytask2 = Task()
        mytask2.keywords.append("two")
        self.assertEqual(mytask2.keywords[0], "two")  

When I ran the test, it failed with the following exception: "AssertionError: 'one' != 'two'". As I dug into the code I found that the mytask and mytask2 instances had received both of the keywords, not just one a piece. My initial reaction was that this must be some sort of Python bug. But as I investigated I found that I had actually created a Class Variable - Python's way of saying "static". What I really wanted was an Instance Variable.

class Task(object):
    def __init__(self):
        self.keywords = []

By declaring "keywords" inside the constructor it is now guaranteed to be unique to each instance of the class allowing my test to pass. This link in the Python Reference Manual explains it much more clearly. Note that IronPython behaves in the same manner.

Published Friday, September 05, 2008 11:41 AM by dhawley

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)