VSCode、Python3.7:自定义装饰的 pylint 无成员错误 class

VSCode, Python3.7: pylint no-member error with custom decorated class

我最近将一个实例方法从其 class 定义中移出,并将它作为一个全局函数(例如:deco_function)以便能够在不同的 class 中使用它] 又是。详细解释和bug复现见以下代码:

def deco_function(cls):
    
    def inner_fct(self):
        print('do something')

    cls.deco_function = inner_fct
    return cls

@deco_function
class Something:

    def __init__(self):
        print('init')
        self.deco_function()
        print('done')

if __name__ == '__main__':
    a = Something()

代码运行完全正常,正在打印

init
do something
done

但是,VSCode 下划线 self.deco_function() 红色,pylint 说明实例 'Something' 没有 'deco_function' 成员。

是否有解决方法,防止 pylint 标记它或使 VSCode 将 deco_function 识别为实例成员?

感谢任何建议。

您必须使用 PyLint 插件来判断哪些 class 成员是运行时生成的

PYTHONPATH

的某处创建一个文件 pylint_decorator.py
import astroid
from astroid import MANAGER

def register(linter):
  # Needed for registering the plugin.
  pass

def transform(cls):
  if not cls.decorators: return
  if any(map(lambda x: x.name == 'deco_function', cls.decorators.nodes)):
    extension_module = astroid.parse("""
def deco_function(self):
  pass
""")
    for name, objs in extension_module.locals.items():
      cls.locals[name] = objs

MANAGER.register_transform(astroid.ClassDef, transform)

然后使用以下设置配置 VSC

"python.linting.pylintArgs": ["--load-plugins", "pylint_decorator"]

这仅在您使用 @deco_function 语法时有效。

如果调用装饰器函数PyLint将看不到装饰器的使用

# this use will not be catched by the plugin
class Something:
    def __init__(self):
        print('init')
        self.deco_function()
        print('done')
Something = deco_function(Something)