pastas / pastastore

:spaghetti: :convenience_store: Tools for managing timeseries and Pastas models
https://pastastore.readthedocs.io
MIT License
15 stars 4 forks source link

potential memory leak issue using lru_cache #128

Open dbrakenhoff opened 1 month ago

dbrakenhoff commented 1 month ago

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