0
class A:
    @cache
    def extremely_long_and_expensive_function(self) -> None:
        # series of instructions that MUST access self

Pylint complains as follows:

lru_cache(maxsize=None)' or 'cache' will keep all method args alive indefinitely, including 'self'pylint(method-cache-max-size-none)

But I could not find a satisfying solution online that actually tells me how to cache that method without having to create some contrived rube-goldberg machine. How do I memoize expensive_function so that the method is run exactly once and no more, no matter how many times I launch it?

Others have suggested using @cached_property, but this is not a property, so it feels wrong to write A().expensive_function. It's a function that executes initialization commands that are not always needed in every instance, and it doesn't return anything, so it should not be a property.

Surely there's some simple way to do this that I'm missing, I don't want to believe that such a simple use case requires a Frankenstein reimplementation like the answer in https://stackoverflow.com/a/33672499/11558993.

Some Guy
  • 576
  • 1
  • 4
  • 17
  • There are a number of implementations in the linked post that don't seem complicated. Do you call them Frankenstein because of their implementation of because of how they are used. Implementation aside, this seems dead simple assuming it works.. `from methodtools import lru_cache` – JonSG Feb 02 '23 at 15:27
  • This is a simple enough case that i would expect the built-in libraries to be able to handle it natively. The question is also quite old, while the pylint warning is fairly new afaik, which is why I opened this question. – Some Guy Feb 02 '23 at 15:38

0 Answers0