[issue45588] cached_method similar to cached_property to cache with classes
Marten Lienen
report at bugs.python.org
Sat Oct 23 11:53:25 EDT 2021
Marten Lienen <marten.lienen at gmail.com> added the comment:
An implementation based on cached_property (that therefore also inherits its locking problem) that does not create a circular reference and copies attributes (docs etc.) from the decorated function would be as follows (based on the WeaklyBoundMethod from this PR).
def cached_method_inner(func, lru_args):
lru_args.setdefault("maxsize", None)
def binder(self):
method = WeaklyBoundMethod(func.__get__(self))
cache = lru_cache(**lru_args)
cached = cache(method)
update_wrapper(cached, func)
return cached
prop = cached_property(binder)
update_wrapper(prop, func)
return prop
def cached_method(func=None, /, **lru_args):
if func is not None:
return cached_method_inner(func, lru_args)
else:
def decorator(late_func):
return cached_method_inner(late_func, lru_args)
return decorator
----------
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45588>
_______________________________________
More information about the Python-bugs-list
mailing list