Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2011
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.79 KB | None | 0 0
  1. import random
  2.  
  3. def cached_property(method):
  4.  
  5.     method.cache = {}
  6.     def caching_method(self, *args, **kwargs):
  7.         key = '%s__%s' % (hex(id(self)), method.__name__)
  8.  
  9.         try:
  10.             cache = method.cache
  11.         except AttributeError:
  12.             cache = method.cache = {}
  13.  
  14.         try:
  15.             value = cache[key]
  16.         except KeyError:
  17.             value = method(self, *args, **kwargs)
  18.             cache[key] = value
  19.         return value
  20.  
  21.     caching_method.__doc__ = method.__doc__
  22.     caching_method.__name__ = method.__name__
  23.     caching_method.__module__ = method.__module__
  24.  
  25.     return property(caching_method)
  26.  
  27. class SuperSafe(object):
  28.  
  29.     @cached_property
  30.     def value(self):
  31.         """Some docstring."""
  32.         return random.randint(1, 10)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement