我最近将一个实例方法移出了它的类定义,并将其作为全局函数(例如: deco_function),以便能够在不同的类中再次使用它。详细解释和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识别为实例成员?
谢谢你的建议。
发布于 2020-11-11 22:52:51
您必须使用PyLint插件来确定哪些类成员是在运行时生成的
在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)https://stackoverflow.com/questions/64788077
复制相似问题