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

Alo*_*lon 5 python pylint

我的代码使用werkzeug中常用的cached_property类。考虑以下片段:

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
Run Code Online (Sandbox Code Playgroud)

我在 CI 过程中使用 pylint。如果我对此代码运行 pylint不可迭代检查,即使代码完全正常,它也会失败。

$ 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)
Run Code Online (Sandbox Code Playgroud)

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

class SampleClass(object):
    @property
    def list_prop(self):
        return [1, 2]
Run Code Online (Sandbox Code Playgroud)

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

Sri*_*nth 3

看来您导入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
Run Code Online (Sandbox Code Playgroud)

当我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)
Run Code Online (Sandbox Code Playgroud)