Skip to content

potential memory leak issue using lru_cache #128

Description

@dbrakenhoff

Ruff complains about a memory leak issue using lru_cache on class methods.

Solution according to some brilliant mind on stackoverflow is below. Now I need to figure out how to clear the cache using this decorator.

def weak_lru(maxsize=128, typed=False):
    """LRU Cache decorator that keeps a weak reference to 'self'.

    From https://stackoverflow.com/a/68052994/10596229.

    Parameters
    ----------
    maxsize : int, optional
        maximum size of cache, by default 128
    typed : bool, optional
        whether to differentiate between types, by default False

    """

    def wrapper(func):
        @functools.lru_cache(maxsize, typed)
        def _func(_self, *args, **kwargs):
            return func(_self(), *args, **kwargs)

        @functools.wraps(func)
        def inner(self, *args, **kwargs):
            return _func(weakref.ref(self), *args, **kwargs)

        return inner

    return wrapper

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions