method-cache-max-size-none / W1518ΒΆ
Message emitted:
'lru_cache(maxsize=None)' or 'cache' will keep all method args alive indefinitely, including 'self'
Description:
By decorating a method with lru_cache or cache the 'self' argument will be linked to the function and therefore never garbage collected. Unless your instance will never need to be garbage collected (singleton) it is recommended to refactor code to avoid this pattern or add a maxsize to the cache. The default value for maxsize is 128.
Problematic code:
import functools
class Fibonnaci:
def __init__(self):
self.result = []
@functools.lru_cache(maxsize=None) # [method-cache-max-size-none]
def fibonacci(self, n):
if n in {0, 1}:
self.result.append(n)
self.result.append(self.fibonacci(n - 1) + self.fibonacci(n - 2))
Correct code:
import functools
@functools.cache
def cached_fibonacci(n):
if n in {0, 1}:
return n
return cached_fibonacci(n - 1) + cached_fibonacci(n - 2)
class Fibonnaci:
def __init__(self):
self.result = []
def fibonacci(self, n):
self.result.append(cached_fibonacci(n))
Created by the stdlib checker.