A cached property decorator.

Gribouillis Gribouillis is offline Offline Jan 16th, 2009, 6:39 am |
0
This snippet defines a cachedProperty decorator. A cached property differs from a property in that it's value is only computed the first time that the property is accessed and then stored in the object's dict for later use. If the object's attribute is explicitely deleted, it will be computed again the next time it's accessed.
Quick reply to this message  
Python Syntax
  1. #!/usr/bin/env python
  2. # Copyright (c) Gribouillis at www.daniweb.com
  3.  
  4. from functools import update_wrapper
  5.  
  6. def cachedProperty (func ,name =None ):
  7. """cachedProperty(func, name=None) -> a descriptor
  8. This decorator implements an object's property which is computed
  9. the first time it is accessed, and which value is then stored in
  10. the object's __dict__ for later use. If the attribute is deleted,
  11. the value will be recomputed the next time it is accessed.
  12. Usage:
  13. class X(object):
  14. @cachedProperty
  15. def foo(self):
  16. return computation()
  17. """
  18. if name is None :
  19. name =func .__name__
  20. def _get (self ):
  21. try :
  22. return self .__dict__ [name ]
  23. except KeyError :
  24. value =func (self )
  25. self .__dict__ [name ]=value
  26. return value
  27. update_wrapper (_get ,func )
  28. def _del (self ):
  29. self .__dict__ .pop (name ,None )
  30. return property (_get ,None ,_del )
  31.  
  32. if __name__ =="__main__":
  33. # test code for cachedProperty
  34. import time
  35.  
  36. class X (object ):
  37. @cachedProperty
  38. def foo (self ):
  39. print ("--> foo was called")
  40. return time .asctime ()
  41.  
  42. def dictContent (instance ):
  43. return list (sorted (instance .__dict__ ))
  44.  
  45. x =X ()
  46. print (dictContent (x ))# nothing in x.__dict__
  47. print (x .foo )# the attribute is computed and stored in x.__dict__
  48. time .sleep (2 )
  49. print (dictContent (x ))# x.__dict__ has a key 'foo'
  50. print (x .foo )# the cached value is used
  51. print (x .foo )# the cached value is used
  52. del x .foo # the cached value is deleted
  53. print (dictContent (x ))# x.__dict__ doesn't have a 'foo'
  54. print (x .foo )# the attribute is recomputed and stored
  55. print (dictContent (x ))# x.__dict__ has a 'foo'

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC