Skip to content

Instantly share code, notes, and snippets.

@pmslavin
Created June 26, 2015 10:59
Show Gist options
  • Save pmslavin/d95b499e565fb403be15 to your computer and use it in GitHub Desktop.
Save pmslavin/d95b499e565fb403be15 to your computer and use it in GitHub Desktop.
Deepcopy hook demo
import copy
class Parent(object):
def __init__(self):
self.children = []
def addChild(self, child):
self.children.append(child)
def reset(self):
self.children = []
def __str__(self):
ret = ""
for idx, c in enumerate(self.children):
ret += "[{0}] {1}\n".format(idx+1, c)
return ret
class Child(object):
def __init__(self, name):
self.name = name
def __str__(self):
return "{0} {1} at {2:x}".format(self.__class__.__name__, self.name, id(self))
class Unique(Child):
def __deepcopy__(self, memo):
return self
if __name__ == "__main__":
p = Parent()
p.addChild(Child("One"))
p.addChild(Child("Two"))
p.addChild(Child("Three"))
p.addChild(Unique("Unique"))
print("Original Parent has:")
print(p)
p2 = copy.deepcopy(p)
print("Copy Parent has:")
print(p2)
@pmslavin
Copy link
Author

Sample output:

Original Parent has:
[1] Child One at b7669dec
[2] Child Two at b7669e4c
[3] Child Three at b7669e6c
[4] Unique Unique at b7669e8c

Copy Parent has:
[1] Child One at b7669fec
[2] Child Two at b7669fcc
[3] Child Three at 94dc08c
[4] Unique Unique at b7669e8c

Note that the single Unique object created is present in both containers, such that

p.children[3] is p2.children[3]

will evaluate to True.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment