Skip to content

Instantly share code, notes, and snippets.

@fabien-michel
Created October 30, 2019 08:15
Show Gist options
  • Save fabien-michel/8ccf0851fad2ab64e9a9fd3f6ce1da83 to your computer and use it in GitHub Desktop.
Save fabien-michel/8ccf0851fad2ab64e9a9fd3f6ce1da83 to your computer and use it in GitHub Desktop.
Context manager for caching a class method
class LruCacheClassMethod():
def __init__(self, klass, method_name):
self.klass = klass
self.method_name = method_name
self.original_method = getattr(self.klass, self.method_name)
def __enter__(self):
new_method = functools.lru_cache()(self.original_method)
setattr(self.klass, self.method_name, new_method)
return new_method
def __exit__(self, _type, value, traceback):
setattr(self.klass, self.method_name, self.original_method)
class MyClass:
@classmethod
def blop(truc: int):
return truc + 1
with LruCacheClassMethod(MyClass, 'blop'):
print(MyClass.blop(5))
print(MyClass.blop(5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment