禁用给定模块或目录的pylint消息
问题内容:
有没有一种方法可以duplicate- code
仅针对测试文件禁用Pylint的消息?我们项目中的所有测试都是DAMP,因此重复的代码是设计使然的。我知道我们可以在# pylint: disable=duplicate- code
整个测试中添加,但宁愿添加某种规则,该规则说文件test/
夹下的所有文件都将禁用此规则。有没有办法做到这一点?
更具体地说,我正在寻找与“两次运行”解决方案不同的东西(这是我已经依靠的解决方案)。
问题答案:
可以使用pylint插件和一些技巧来实现。
假设我们具有以下目录结构:
pylint_plugin.py
app
├── __init__.py
└── mod.py
test
├── __init__.py
└── mod.py
mod.py的内容:
def f():
1/0
pylint_plugin.py的内容:
from astroid import MANAGER
from astroid import scoped_nodes
def register(linter):
pass
def transform(mod):
if 'test.' not in mod.name:
return
c = mod.stream().read()
# change to the message-id you need
c = b'# pylint: disable=pointless-statement\n' + c
# pylint will read from `.file_bytes` attribute later when tokenization
mod.file_bytes = c
MANAGER.register_transform(scoped_nodes.Module, transform)
没有插件,pylint将报告:
************* Module tmp.exp_pylint.app.mod
W: 2, 4: Statement seems to have no effect (pointless-statement)
************* Module tmp.exp_pylint.test.mod
W: 2, 4: Statement seems to have no effect (pointless-statement)
加载了插件:
PYTHONPATH=. pylint -dC,R --load-plugins pylint_plugin app test
产量:
************* Module tmp.exp_pylint.app.mod
W: 2, 4: Statement seems to have no effect (pointless-statement)
pylint通过对源文件进行标记化来读取注释,此插件可在运行时更改文件内容,以在标记化时欺骗pylint
。
注意,为简化演示,我在这里构造了一个“无意义声明”警告,禁用其他类型的消息是微不足道的。