Guest User

Untitled

a guest
Jul 21st, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. from collections import MutableMapping
  2. from functools import wraps
  3.  
  4. def lazy_load(f):
  5.  
  6. @property
  7. @wraps(f)
  8. def wrapped_fetch(self):
  9. if f.func_name not in self._d:
  10. self._d[f.func_name] = f(self)
  11. print "Grabbing value out of cache"
  12. return self._d[f.func_name]
  13.  
  14. return wrapped_fetch
  15.  
  16. class RequestContext(MutableMapping):
  17.  
  18. def __init__(self, wrapped={}):
  19. self._d = wrapped
  20.  
  21. @lazy_load
  22. def current_user_name(self):
  23. print "Doing some really hard work to fetch the user name"
  24. return "Phill Tornroth"
  25.  
  26. def __getattr__(self, item):
  27. try:
  28. return self.__getitem__(item)
  29. except KeyError:
  30. raise AttributeError(item)
  31.  
  32. def keys(self):
  33. return self._d.keys()
  34.  
  35. # MutableMapping interface methods
  36. def __setitem__(self, key, value):
  37. self._d[key] = value
  38.  
  39. def __delitem__(self, key):
  40. del(self._d[key])
  41.  
  42. def __getitem__(self, key):
  43. return self._d[key]
  44.  
  45. def __len__(self):
  46. return len(self._d)
  47.  
  48. def __iter__(self):
  49. return iter(self._d)
  50.  
  51. def __contains__(self, key):
  52. return key in self._d
  53.  
  54. c = RequestContext()
  55. print c.current_user_name # does the work, and returns cached value
  56. print c.current_user_name # returns cached value.. no more work :)
Add Comment
Please, Sign In to add comment