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.

Revisions

  1. BrandonLMorris created this gist Feb 12, 2016.
    69 changes: 69 additions & 0 deletions mutable_probs.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    """
    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')