Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import MutableMapping
- from functools import wraps
- def lazy_load(f):
- @property
- @wraps(f)
- def wrapped_fetch(self):
- if f.func_name not in self._d:
- self._d[f.func_name] = f(self)
- print "Grabbing value out of cache"
- return self._d[f.func_name]
- return wrapped_fetch
- class RequestContext(MutableMapping):
- def __init__(self, wrapped={}):
- self._d = wrapped
- @lazy_load
- def current_user_name(self):
- print "Doing some really hard work to fetch the user name"
- return "Phill Tornroth"
- def __getattr__(self, item):
- try:
- return self.__getitem__(item)
- except KeyError:
- raise AttributeError(item)
- def keys(self):
- return self._d.keys()
- # MutableMapping interface methods
- def __setitem__(self, key, value):
- self._d[key] = value
- def __delitem__(self, key):
- del(self._d[key])
- def __getitem__(self, key):
- return self._d[key]
- def __len__(self):
- return len(self._d)
- def __iter__(self):
- return iter(self._d)
- def __contains__(self, key):
- return key in self._d
- c = RequestContext()
- print c.current_user_name # does the work, and returns cached value
- print c.current_user_name # returns cached value.. no more work :)
Add Comment
Please, Sign In to add comment