Advertisement
Guest User

Untitled

a guest
May 22nd, 2015
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. #
  4. # Copyright (c) 2008 Doug Hellmann All rights reserved.
  5. #
  6. """Demonstrate WeakValueDictionary.
  7. """
  8. #end_pymotw_header
  9.  
  10. import gc
  11. from pprint import pprint
  12. import weakref
  13.  
  14. gc.set_debug(gc.DEBUG_LEAK)
  15.  
  16. class ExpensiveObject(object):
  17. def __init__(self, name):
  18. self.name = name
  19. def __repr__(self):
  20. return 'ExpensiveObject(%s)' % self.name
  21. def __del__(self):
  22. print ' (Deleting %s)' % self
  23.  
  24. def demo(cache_factory):
  25. # hold objects so any weak references
  26. # are not removed immediately
  27. all_refs = {}
  28. # create the cache using the factory
  29. print 'CACHE TYPE:', cache_factory
  30. cache = cache_factory()
  31. for name in [ 'one', 'two', 'three' ]:
  32. o = ExpensiveObject(name)
  33. cache[name] = o
  34. all_refs[name] = o
  35. del o # decref
  36.  
  37. print ' all_refs =',
  38. pprint(all_refs)
  39. print '\n Before, cache contains:', cache.keys()
  40. for name, value in cache.items():
  41. print ' %s = %s' % (name, value)
  42. del value # decref
  43.  
  44. # Remove all references to the objects except the cache
  45. print '\n Cleanup:'
  46. del all_refs
  47. gc.collect()
  48.  
  49. print '\n After, cache contains:', cache.keys()
  50. for name, value in cache.items():
  51. print ' %s = %s' % (name, value)
  52. print ' demo returning'
  53. return
  54.  
  55. demo(dict)
  56. print
  57.  
  58. demo(weakref.WeakValueDictionary)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement