Skip to content

Instantly share code, notes, and snippets.

@jamalex
Created July 15, 2013 05:46
Show Gist options
  • Save jamalex/5997735 to your computer and use it in GitHub Desktop.
Save jamalex/5997735 to your computer and use it in GitHub Desktop.
Counter-example to the two (otherwise very good) generalizations about Python that "assignment never makes new values, and it never copies data" and "Lots of Python data structures [e.g. object attributes] hold values, and each of those is a reference. All of the rules here about names apply exactly the same to any of these references." (see htt…
from copy import deepcopy
class MagicSetter(object):
def __setattr__(self, name, value):
super(MagicSetter, self).__setattr__(name, deepcopy(value))
m = MagicSetter()
m.a = ["this", "is", "the", "original", "list"]
# an example of simple assignment that does lead to a copy
m.b = m.a
# so even if we change the second list
m.b.insert(2, "not")
# the original list remains unchanged
print " ".join(m.a)
print " ".join(m.b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment