对我来说,pylint 对于实际上是可迭代的 @cached_property 返回错误 E1133(不可迭代)。想知道这是否是 pylint 中的错误,或者我可以采取一些措施来防止出现此错误。
从功能上讲,代码运行没有问题。这意味着我能够迭代这个已识别的不可迭代的。
# doodle.py
from typing import List
from cached_property import cached_property
class Bike:
@cached_property
def tires(self) -> List[str]:
return ["front", "back"]
front_tire = [tire for tire in Bike().tires if tire == "front"]
当使用 @property 使非缓存属性 pylint 按预期工作时。下面的代码块没有出现错误。
class Bike:
@property
def tires(self):
return ["front", "back"]
front_tire = [tire for tire in Bike().tires if tire == "front"]
这是 @cached_property 代码块上引发的 pylint 错误: doodle.py:11:31: E1133: 不可迭代值 Bike().tires 在迭代上下文中使用(不可迭代)
只是我想提一下,我不想用
pylint: disable=not-an-iterable
来抑制错误
您可以使用内置的
cached-property
,而不是使用
functools.cached_property
库:
# Simply replace this
from cached_property import cached_property
# by this
from functools import cached_property
该函数的工作原理完全相同,但 Pylint 可以正确识别类型。
如果您的环境中未安装
not-an-iterable
,则可能会发出 cached_property
消息;我已经重现了此消息,并且使用 pip install cached_property
安装后不再发出该消息。
使用以下 Pylint 版本进行测试:
pylint --version
pylint 2.15.5
astroid 2.12.12
Python 3.10.4