Skip to content

Instantly share code, notes, and snippets.

@agutoli
Last active February 6, 2020 14:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agutoli/0b9cdd3b0893a40821645155f9b2d917 to your computer and use it in GitHub Desktop.
Save agutoli/0b9cdd3b0893a40821645155f9b2d917 to your computer and use it in GitHub Desktop.
python, cache, decorator
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