Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

potential memory leak issue using lru_cache #128

Open
dbrakenhoff opened this issue Jul 9, 2024 · 0 comments
Open

potential memory leak issue using lru_cache #128

dbrakenhoff opened this issue Jul 9, 2024 · 0 comments

Comments

@dbrakenhoff
Copy link
Member

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant