Created
July 15, 2013 05:46
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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