跳到内容

cached-instance-method (B019) (缓存实例方法 (B019))

源自 flake8-bugbear linter。

作用

Checks for uses of the functools.lru_cache and functools.cache decorators on methods. (检查方法中 functools.lru_cachefunctools.cache 装饰器的使用。)

为什么这不好?

Using the functools.lru_cache and functools.cache decorators on methods can lead to memory leaks, as the global cache will retain a reference to the instance, preventing it from being garbage collected. (在方法上使用 functools.lru_cachefunctools.cache 装饰器可能会导致内存泄漏,因为全局缓存将保留对实例的引用,从而阻止其被垃圾回收。)

Instead, refactor the method to depend only on its arguments and not on the instance of the class, or use the @lru_cache decorator on a function outside of the class. (相反,应该重构该方法,使其仅依赖于其参数,而不依赖于类的实例,或者在类外部的函数上使用 @lru_cache 装饰器。)

This rule ignores instance methods on enumeration classes, as enum members are singletons. (此规则忽略枚举类上的实例方法,因为枚举成员是单例。)

示例

from functools import lru_cache


def square(x: int) -> int:
    return x * x


class Number:
    value: int

    @lru_cache
    def squared(self):
        return square(self.value)

建议改为

from functools import lru_cache


@lru_cache
def square(x: int) -> int:
    return x * x


class Number:
    value: int

    def squared(self):
        return square(self.value)

参考