Skip to content

Instantly share code, notes, and snippets.

@BrandonLMorris
Created February 12, 2016 14:54
Show Gist options
  • Save BrandonLMorris/12c202a414b70c88a6be to your computer and use it in GitHub Desktop.
Save BrandonLMorris/12c202a414b70c88a6be to your computer and use it in GitHub Desktop.
Demonstrating a gotcha of Python mutable types
"""
Simple demonstration of the gotcha that can occur in Python with mutable
types being shared across instances of a class
Taken with slight modification from the Python Guide
http://docs.python-guide.org/en/latest/writing/gotchas/
(The same thing applies to default arguments)
"""
class Test(object):
lst = []
def print_lst(self):
print(self.lst)
def add_to_lst(self, x):
self.lst.append(x)
class OtherTest(object):
def __init__(self, *args, **kwargs):
self.lst = []
def print_lst(self):
print(self.lst)
def add_to_lst(self, x):
self.lst.append(x)
""" Program driver """
if __name__ == '__main__':
test1, test2 = Test(), Test()
print('Appending 1, 2, and 3 to test1')
test1.add_to_lst(1); test1.add_to_lst(2); test1.add_to_lst(3)
print('test1.print_lst()')
test1.print_lst()
print()
print('test2.print_lst()')
test2.print_lst()
print()
print('As you can see, the list in test2 contained the same elements\n'
'as the list in test1 because they point to the same object\n'
'since they were defined at the class level\n')
print('Now we\'ll do the same thing with the OtherTest class, where\n'
'the list was defined in the __init__ method\n')
test1, test2 = OtherTest(), OtherTest()
print('Appending 1, 2, and 3 to test1')
test1.add_to_lst(1); test1.add_to_lst(2); test1.add_to_lst(3)
print('test1.print_lst()')
test1.print_lst()
print()
print('test2.print_lst()')
test2.print_lst()
print()
print('Now the two objects have two separate lists, independent of\n'
'each other')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment