Created
October 30, 2019 08:15
-
-
Save fabien-michel/8ccf0851fad2ab64e9a9fd3f6ce1da83 to your computer and use it in GitHub Desktop.
Context manager for caching a class method
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
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