禁用给定模块或目录的 pylint 消息 [英] Disable pylint message for a given module or directory
问题描述
有没有办法仅针对测试文件禁用 Pylint 的 duplicate-code
消息?我们项目中的所有测试都是 DAMP,因此重复的代码是设计使然.我知道我们可以在整个测试中添加 # pylint: disable=duplicate-code
,但宁愿添加某种规则,说明 test/
文件夹下的所有文件都将具有此规则已禁用.有没有办法做到这一点?
Is there a way to disable Pylint's duplicate-code
message just for test files? All of the tests in our project are DAMP so the duplicated code is by design. I understand we can add # pylint: disable=duplicate-code
throughout our tests, but would rather add some sort of rule that says all files under a test/
folder will have this rule disabled. Is there a way to do this?
更具体地说,我正在寻找与运行两次"解决方案不同的东西(这是我已经依赖的解决方案).
To be more specific, I'm looking for something different from a 'run it twice' solution (which is what I've already fallen back on).
推荐答案
可以通过pylint插件和一些hack来实现.
It can be achieved with pylint plugin and some hack.
假设我们有以下目录结构:
Assume we have following directory structure:
pylint_plugin.py
app
├── __init__.py
└── mod.py
test
├── __init__.py
└── mod.py
mod.py 的内容:
content of mod.py:
def f():
1/0
pylint_plugin.py 的内容:
content of 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会报:
without plugin, pylint will report:
************* 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 read comments by tokenizing source file, this plugin change file content on the fly, to cheat pylint when tokenization.
注意为了简化演示,这里我构造了一个pointless-statement"警告,禁用其他类型的消息是微不足道的.
Note that to simplify demonstration, here I constructed a "pointless-statement" warning, disable other types of message is trivial.
这篇关于禁用给定模块或目录的 pylint 消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!