Message396178
Adding a weak referencing recipe here just so I can find it in the future.
--------------------------------------------------------------------------
import functools
import weakref
def weak_lru(maxsize=128, typed=False):
"""LRU Cache decorator that keeps a weak reference to "self".
Only provides benefit if the instances are so large that
it is impractical to wait for them to age out of the cache.
When the instance is freed, the cache entry still remains
but will be unreachable.
If new instances will be created that are equal to the ones
retired by the weak reference, we lose all the benefits of
having cached the previous call.
If the class defines __slots__, be sure to add '__weakref__'
to make the instances weak referenceable.
"""
def decorator(func):
ref = weakref.ref
@functools.lru_cache(maxsize, typed)
def _func(_self, /, *args, **kwargs):
return func(_self(), *args, **kwargs)
@functools.wraps(func)
def wrapper(self, /, *args, **kwargs):
return _func(ref(self), *args, **kwargs)
return wrapper
return decorator |
|
Date |
User |
Action |
Args |
2021-06-20 15:11:01 | rhettinger | set | recipients:
+ rhettinger, python-dev, serhiy.storchaka, cryvate, pablogsal, miss-islington, nanjekyejoannah, Wouter De Borger2, kj |
2021-06-20 15:11:01 | rhettinger | set | messageid: <1624201861.9.0.774635737438.issue44310@roundup.psfhosted.org> |
2021-06-20 15:11:01 | rhettinger | link | issue44310 messages |
2021-06-20 15:11:01 | rhettinger | create | |
|