Created
March 9, 2011 19:12
-
-
Save mrts/862768 to your computer and use it in GitHub Desktop.
Thread safe descriptor that combines memoizing (caching) and lazy loading
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LazyCachedDescriptor(object): | |
def __init__(self, fn, *args, **kwargs): | |
self.cache = None | |
self.fn = fn | |
self.args = args | |
self.kwargs = kwargs | |
def __get__(self, obj, objtype): | |
if self.cache is None: | |
result = [self.fn(*self.args, **self.kwargs)] | |
self.cache = result | |
return self.cache[0] | |
def reset(self): | |
self.cache = None | |
def func(*args, **kwargs): | |
print "func() was called with %s and %s" % (args, kwargs) | |
return "func() returned foo" | |
class consts(object): | |
FOO = LazyCachedDescriptor(func, 1, 'foo', b=3) | |
@classmethod | |
def reset(cls, attrib_name): | |
cls.__dict__[attrib_name].reset() | |
print consts.FOO | |
print consts.FOO | |
consts.reset('FOO') | |
print consts.FOO | |
print consts.FOO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment