Advertisement
rfmonk

copy_recursion.py

Jan 15th, 2014
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import copy
  5. import pprint
  6.  
  7.  
  8. class Graph:
  9.  
  10.     def __init__(self, name, connections):
  11.         self.name = name
  12.         self.connections = connections
  13.  
  14.     def add_connection(self, other):
  15.         self.connections.append(other)
  16.  
  17.     def __repr__(self):
  18.         return 'Graph(name=%s, id=%s)' % (self.name, id(self))
  19.  
  20.     def __deepcopy__(self, memo):
  21.         print '\nCalling __deepcopy__ for %r' % self
  22.         if self in memo:
  23.             existing = memo.get(self)
  24.             print ' Already copied to %r' % existing
  25.             return existing
  26.         print ' Memo dictionary:'
  27.         pprint.pprint(memo, indent=4, width=40)
  28.         dup = Graph(copy.deepcopy(self.name, memo), [])
  29.         print ' Copying to a new object %s' % dup
  30.         memo[self] = dup
  31.         for c in self.connections:
  32.             dup.add_connection(copy.deepcopy(c, memo))
  33.         return dup
  34.  
  35. root = Graph('root', [])
  36. a = Graph('a', [root])
  37. b = Graph('b', [a, root])
  38. root.add_connection(a)
  39. root.add_connection(b)
  40.  
  41. dup = copy.deepcopy(root)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement