使用自定义 属性 class 时如何避免 pylint 不可迭代

How to avoid pylint not-an-iterable when using a custom property class

我的代码使用了常用的cached_property class from werkzeug。考虑以下片段:

from werkzeug import cached_property

class SampleClass(object):
    @cached_property
    def list_prop(self):
        return [1, 2]

sample = SampleClass()
for item in sample.list_prop:
    print item

我在 CI 进程中使用 pylint。如果我 运行 pylint not-an-iterable 检查此代码,即使代码完全正常,它也会失败。

$ pylint --disable=all --enable=not-an-iterable prop.py
************* Module prop
E:  9,12: Non-iterable value sample.list_prop is used in an iterating context (not-an-iterable)

pylint 在使用内置 @property 装饰器而不是 @cached_property 检查相同代码时效果很好:

class SampleClass(object):
    @property
    def list_prop(self):
        return [1, 2]

我应该怎么做才能帮助 pylint 克服这种误报?

看起来您导入的 cached_property 不正确。它住在 werkzeug.utilspylint 发现错误:E: 1, 0: No name 'cached_property' in module 'werkzeug' (no-name-in-module)。这是固定代码:

from werkzeug.utils import cached_property

class SampleClass(object):
    @cached_property
    def list_prop(self):
        return [1, 2]

sample = SampleClass()
for item in sample.list_prop:
    print item

当我 运行 pylint 应用此修复后,它停止抱怨:

$ pylint test
No config file found, using default configuration
************* Module test
C:  1, 0: Missing module docstring (missing-docstring)
C:  3, 0: Missing class docstring (missing-docstring)
C:  5, 4: Missing method docstring (missing-docstring)
R:  3, 0: Too few public methods (1/2) (too-few-public-methods)
C:  8, 0: Invalid constant name "sample" (invalid-name)

我在使用 Django+ pylint 时遇到同样的问题: 代码如下:

queryset = A.objects.filter(col_a='a',col_b='b')

它会显示错误信息:

Non-iterable value queryset is used in an iterating context (not-an-iterable)

我的解决方法如下(+all()):

queryset = A.objects.filter(col_a='a',col_b='b').all()

它实际上解决了我的问题,我知道它似乎与问题没有太大关系但是我 google 'pylint + Non-iterable',这个页面将在搜索结果的顶部,所以我想把解决方案放在这里,谢谢