Created
October 28, 2013 18:52
-
-
Save carymrobbins/7202467 to your computer and use it in GitHub Desktop.
Lazy method decorator that allows you to cache the results of function calls with unhashable arguments.
This file contains 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 lazy_method(object): | |
""" Allows you to cache unhashable arguments. """ | |
@classmethod | |
def truncate(cls, obj): | |
""" Removes method cache from obj. """ | |
if hasattr(obj, '_lazy_items'): | |
del obj._lazy_items | |
def __init__(self, f): | |
def wrapped(self, *args, **kwargs): | |
if not hasattr(self, '_lazy_items'): | |
self._lazy_items = [] | |
packed = (f.__name__, args, kwargs) | |
try: | |
result = next(v for k, v in self._lazy_items if k == packed) | |
except StopIteration: | |
result = f(self, *args, **kwargs) | |
self._lazy_items.append((packed, result)) | |
return result | |
wrapped.__name__ = f.__name__ | |
self.function = wrapped | |
def __call__(self, *args, **kwargs): | |
return self.function(*args, **kwargs) | |
def __get__(self, obj, obj_type): | |
return partial(self.__call__, obj) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment