Created
April 30, 2015 07:54
-
-
Save cstrap/a6444b32ee0c5195ab0b to your computer and use it in GitHub Desktop.
Memoize with Python 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
| # -*- coding: utf-8 -*- | |
| from functools import wraps | |
| def memoize(obj): | |
| """ | |
| From Python Decorator Library | |
| """ | |
| cache = obj.cache = {} | |
| @wraps(obj) | |
| def memoizer(*args, **kwargs): | |
| key = str(args) + str(kwargs) | |
| if key not in cache: | |
| cache[key] = obj(*args, **kwargs) | |
| return cache[key] | |
| return memoizer | |
| def memoize_method(obj): | |
| """ | |
| memoize class method adding a property to the class instance | |
| """ | |
| @wraps(obj) | |
| def memoizer(*args, **kwargs): | |
| instance = args[0] | |
| cache_method = '_{}_cache'.format(obj.__name__) | |
| key = args[1:] + tuple(sorted(kwargs.items())) | |
| if not hasattr(instance, cache_method): | |
| setattr(instance, cache_method, {}) | |
| _cache = getattr(instance, cache_method) | |
| if key not in _cache: | |
| _cache[key] = obj(*args, **kwargs) | |
| return _cache[key] | |
| return memoizer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment