Advertisement
rfmonk

weakref_graph.py

Jan 15th, 2014
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import gc
  5. from pprint import pprint
  6. import weakref
  7.  
  8.  
  9. class Graph(object):
  10.     def __init__(self, name):
  11.         self.name = name
  12.         self.other = None
  13.  
  14.     def set_next(self, other):
  15.         print '%s.set_next(%r)' % (self.name, other)
  16.         self.other = other
  17.  
  18.     def all_nodes(self):
  19.         "Generate the nodes in the graph sequence."
  20.         yield self
  21.         n = self.other
  22.         while n and n.name != self.name:
  23.             yield n
  24.             n = n.other
  25.         if n is self:
  26.             yield n
  27.         return
  28.  
  29.     def __str__(self):
  30.         return '->'.join(n.name for n in self.all_nodes())
  31.  
  32.     def __repr__(self):
  33.         return '<%s at 0x%x name=%s>' % (self.__class__.__name__,
  34.                                          id(self), self.name)
  35.  
  36.     def __del__(self):
  37.         print '(Deleting %s)' % self.name
  38.         self.set_next(None)
  39.  
  40.  
  41. def collect_and_show_garbage():
  42.     "Show what garbage is present."
  43.     print 'Collecting...'
  44.     n = gc.collect()
  45.     print 'Unreachable objects:', n
  46.     print 'Garbage:',
  47.     pprint(gc.garbage)
  48.  
  49.  
  50. def demo(graph_factory):
  51.     print 'Set up graph:'
  52.     one = graph_factory('one')
  53.     two = graph_factory('two')
  54.     three = graph_factory('three')
  55.     one.set_next(two)
  56.     two.set_next(three)
  57.     three.set_next(one)
  58.  
  59.     print
  60.     print 'Graph:'
  61.     print str(one)
  62.     collect_and_show_garbage()
  63.  
  64.     print
  65.     three = None
  66.     two = None
  67.     print 'After 2 references removed:'
  68.     print str(one)
  69.     collect_and_show_garbage()
  70.  
  71.     print
  72.     print 'Removing last reference:'
  73.     one = None
  74.     collect_and_show_garbage()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement