短版本:--如果我定义了一个装饰符来在运行时导入一个模块并在func_globals中为一个方法声明它,我如何告诉Pylint已经定义了结果变量?
长版本:考虑以下示例:
from importlib import import_module
def with_import(module):
modname = module.split('.')[-1]
def decorate(func):
def wrapper(*args, **kwargs):
func.func_globals[modname] = import_module(module)
return func(*args, **kwargs)
return wrapper
return decorate
@with_import('numpy')
def create_array(n):
return numpy.empty(n)
print(create_array(5))这段代码工作得很好,因为with_import装饰器为create_array函数声明了numpy。然而,当我运行PyLint时,我看到
E: 16,11: Undefined variable 'numpy' (undefined-variable)有没有办法告诉Pylint这个变量实际上是在运行时定义的?我真的不想禁用整个模块的unused-variable检查,以防有人在以后的某个日期声明一个常规的未使用的变量。
发布于 2017-02-14 17:08:35
例如,可以在块或行基础上禁用检查。
def f():
# pylint: disable=E0602
x[0] = 5
y[0] = 5
# No errors
def f():
x[0] = 5 # pylint: disable=E0602
y[0] = 5
# Only y will raise the undefined variable error对于装潢师,你有一个相当于第一个的,我很惊讶它的效果,我觉得它很难看,但是:
@deco
# pylint: disable=E0602
def f():
x[0] = 5 # No error here
y[0] = 5 # Error here注意,在pylint报告中将有一个I: Locally disabling undefined-variable (E0602)
发布于 2021-03-09 11:48:38
pylint关注typing.TYPE_CHECKING。所以你可以:
import typing
if typing.TYPE_CHECKING:
import numpy
@with_import('numpy')
def create_array(n):
return numpy.empty(n)typing.TYPE_CHECKING在运行时总是错误的,因此导入不会被运行。但是,pylint假设typing.TYPE_CHECKING是真的,并将分析代码,就像导入已经执行一样。
发布于 2017-02-14 17:18:25
只在发生的确切行中禁用它:
@with_import('numpy')
def create_array(n):
return numpy.empty(n) # pylint: disable=undefined-variablehttps://stackoverflow.com/questions/42230858
复制相似问题