Created
October 21, 2015 21:03
-
-
Save Terrance/0ca842fe18273a38d18e to your computer and use it in GitHub Desktop.
A Python decorator for caching a function result on first call (e.g. for network requests). Works well with the property decorator.
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
| from functools import wraps | |
| from inspect import getargspec | |
| def cacheResult(fn): | |
| cacheAttr = "{0}Cache".format(fn.__name__) | |
| argSpec = getargspec(fn) | |
| argNames = argSpec.args[1:] | |
| if len(argNames) > 1: | |
| raise RuntimeError("can't cache results if function takes multiple args") | |
| argName = argNames[0] if len(argNames) else None | |
| if argName: | |
| if argSpec.defaults: | |
| @wraps(fn) | |
| def wrapper(self, arg=argSpec.defaults[0]): | |
| if not hasattr(self, cacheAttr): | |
| setattr(self, cacheAttr, {}) | |
| cache = getattr(self, cacheAttr) | |
| if arg not in cache: | |
| cache[arg] = fn(self, arg) | |
| return cache[arg] | |
| else: | |
| @wraps(fn) | |
| def wrapper(self, arg): | |
| if not hasattr(self, cacheAttr): | |
| setattr(self, cacheAttr, {}) | |
| cache = getattr(self, cacheAttr) | |
| if arg not in cache: | |
| cache[arg] = fn(self, arg) | |
| return cache[arg] | |
| else: | |
| @wraps(fn) | |
| def wrapper(self): | |
| if not hasattr(self, cacheAttr): | |
| setattr(self, cacheAttr, fn(self)) | |
| return getattr(self, cacheAttr) | |
| return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment