Advertisement
Guest User

Untitled

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