I have a class with a method that I want to cache properly, i.e. that the results are properly cleaned when the object is no longer in use. Example:
import functools
import numpy as np
class foo:
def __init__(self, dev):
self.dev = dev
@functools.cache
def bar(self, len):
return np.random.normal(scale=self.dev, size=len)
if __name__ == '__main__':
for i in range(100000):
foo = Foo(i)
_ = foo.bar(1000000)
This creates a memory leak which is hard to discover. How to do this properly? For properties, there is a cached_property
, but this does not work for functions with arguments.