Skip to content

Instantly share code, notes, and snippets.

@phill-tornroth
Created January 27, 2011 22:51
Show Gist options
  • Save phill-tornroth/799471 to your computer and use it in GitHub Desktop.
Save phill-tornroth/799471 to your computer and use it in GitHub Desktop.
Spun up a little decorator to lazy load properties that I wanted pinned to my context object. I'm using this in the context of a web request object, where I want to make things like request.current_whatever available, but I don't want to pay the penalty f
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 :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment