Raymond Hettinger <raymond.hettin...@gmail.com> added the comment:

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

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue44310>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to