Last active
February 6, 2020 14:54
-
-
Save agutoli/0b9cdd3b0893a40821645155f9b2d917 to your computer and use it in GitHub Desktop.
python, cache, decorator
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
def cache(func): | |
attr = '_cls_cache_' | |
def wrapper(*args, **kwargs): | |
cls = args[0] | |
key = str(args[1:]) + str(kwargs) | |
if not hasattr(cls, attr): | |
setattr(cls, attr, {}) | |
_cache = getattr(cls, attr) | |
if key in _cache: | |
return _cache[key] | |
_cache[key] = func(*args, **kwargs) | |
return _cache[key] | |
func(*args) | |
return wrapper | |
class Example: | |
@cache | |
def my_big_o_2(self, input): | |
for ... in ...: | |
for ... in ...: | |
return something | |
def my_entry_func(self): | |
self.my_big_o_2('my_input') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment