This repository provides a Python decorator @cached_method that caches method results similar to functools.lru_cache, but with each instance having its own cache.
The cached_method decorator allows you to cache the results of an instance method call so that subsequent calls with the same arguments will return the cached result instead of performing the computation again.
This decorator provides two key benefits:
- The cache is cleared when the instance is garbage collected (by using weak references).
- The instance (
self) is not used as a key, so instances can be unhashable.
However, there is a trade-off:
- The cache is not shared between instances.
You can use this decorator in your Python class as follows:
class MyClass:
@cached_method
def my_method(self, arg):
print("Computing...")
return argWhen you call a method decorated with @cached_method, the first call to the method with a particular set of arguments will perform the computation and cache the result:
mc1 = MyClass()
mc1.my_method(1) # "Computing..." is printed, result is computed and cachedSubsequent calls with the same arguments will return the cached result:
mc1.my_method(1) # Result is returned from cache, no computationDifferent class instances will have different caches:
mc2 = MyClass()
mc2.my_method(1) # "Computing..." is printed, result is computed and cached for mc2
mc2.my_method(1) # Result is returned from mc2's cacheYou can clear the cache as follows:
mc1.my_method.cache_clear() # Clears the cache for mc1.my_methodNote: The cache is stored on the instance. Attempting to access the cache on the class or function will raise an AttributeError.
Finally, the cache will be cleared when the instance is garbage collected:
mc1_weak = weakref.ref(mc1)
del mc1
assert mc1_weak() is None # True, since instance has been garbage collectedYou can pass the same arguments to @cached_method as you would to functools.lru_cache to customize the caching behavior, such as maxsize for limiting the size of the cache and typed for storing different results for different types of arguments.