This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author rhettinger
Recipients Wouter De Borger2, cryvate, kj, miss-islington, nanjekyejoannah, pablogsal, python-dev, rhettinger, serhiy.storchaka
Date 2021-06-20.15:11:01
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1624201861.9.0.774635737438.issue44310@roundup.psfhosted.org>
In-reply-to
Content
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
History
Date User Action Args
2021-06-20 15:11:01rhettingersetrecipients: + rhettinger, python-dev, serhiy.storchaka, cryvate, pablogsal, miss-islington, nanjekyejoannah, Wouter De Borger2, kj
2021-06-20 15:11:01rhettingersetmessageid: <1624201861.9.0.774635737438.issue44310@roundup.psfhosted.org>
2021-06-20 15:11:01rhettingerlinkissue44310 messages
2021-06-20 15:11:01rhettingercreate