Advertisement
rfmonk

weakref_valuedict.py

Jan 15th, 2014
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import gc
  5. from pprint import pprint
  6. import weakref
  7.  
  8. gc.set_debug(gc.DEBUG_LEAK)
  9.  
  10.  
  11. class ExpensiveObject(object):
  12.     def __init__(self, name):
  13.         self.name = name
  14.  
  15.     def __repr__(self):
  16.         return 'ExpensiveObject(%s)' % self.name
  17.  
  18.     def __del__(self):
  19.         print ' (Deleting %s)' % self
  20.  
  21.  
  22. def demo(cache_factory):
  23.     all_refs = {}
  24.     print 'CACHE TYPE:', cache_factory
  25.     cache = cache_factory()
  26.     for name in ['one', 'two', 'three']:
  27.         o = ExpensiveObject(name)
  28.         cache[name] = o
  29.         all_refs[name] = o
  30.         del o  # decref
  31.  
  32.     print '    all_refs =',
  33.     pprint(all_refs)
  34.     print '\n Before, cache contains:', cache.keys()
  35.     for name, value in cache.items():
  36.         print ' %s = %s' % (name, value)
  37.         del value  # decref
  38.  
  39.     # Remove all references to the objects except the cache
  40.     print '\n Cleanup:'
  41.     del all_refs
  42.     gc.collect()
  43.  
  44.     print '\n After, cache contains:', cache.keys()
  45.     for name, value in cache.items():
  46.         print '     %s = %s' % (name, value)
  47.     print ' demo returning'
  48.     return
  49.  
  50. demo(dict)
  51. print
  52.  
  53. demo(weakref.WeakValueDictionary)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement