简体   繁体   English

如何禁用 Pylint 警告?

[英]How do I disable a Pylint warning?

I'm trying to disable warning C0321 ("more than one statement on a single line" -- I often put if statements with short single-line results on the same line), in Pylint 0.21.1 (if it matters: astng 0.20.1, common 0.50.3, and Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)).我正在尝试在 Pylint 0.21.1 中禁用警告 C0321(“单行上有多个语句”——我经常将带有短单行结果的if语句放在同一行)(如果重要的话:astng 0.20 .1、通用 0.50.3 和 Python 2.6.6(r266:84292,2010 年 9 月 15 日,16:22:56))。

I've tried adding disable=C0321 in the Pylint configuration file, but Pylint insists on reporting it anyway.我尝试在 Pylint 配置文件中添加disable=C0321 ,但 Pylint 仍然坚持要报告它。 Variations on that line (like disable=0321 or disable=C321 ) are flagged as errors, so Pylint does recognize the option properly.该行的变化(如disable=0321disable=C321 )被标记为错误,因此 Pylint确实正确识别该选项。 It's just ignoring it.它只是忽略它。

Is this a Pylint bug, or am I doing something wrong?这是一个 Pylint 错误,还是我做错了什么? Is there a way around this?有没有解决的办法?

I'd really like to get rid of some of this noise.我真的很想摆脱一些这种噪音。

pylint --generate-rcfile shows it like this: pylint --generate-rcfile显示如下:

[MESSAGES CONTROL]

# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time.
#enable=

# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once).
#disable=

So it looks like your ~/.pylintrc should have the disable= line/s in it inside a section [MESSAGES CONTROL] .所以看起来你的~/.pylintrc应该在[MESSAGES CONTROL]部分中有disable= line/s 。

Starting from Pylint v. 0.25.3, you can use the symbolic names for disabling warnings instead of having to remember all those code numbers .从 Pylint v. 0.25.3 开始,您可以使用符号名称来禁用警告,而不必记住所有这些代码编号 Eg:例如:

# pylint: disable=locally-disabled, multiple-statements, fixme, line-too-long

This style is more instructive than cryptic error codes, and also more practical since newer versions of Pylint only output the symbolic name, not the error code.这种风格比神秘的错误代码更有指导意义,也更实用,因为新版本的 Pylint 只输出符号名称,而不是错误代码。

The correspondence between symbolic names and codes can be found here .符号名称和代码之间的对应关系可以在这里找到。

A disable comment can be inserted on its own line, applying the disable to everything that comes after in the same block.禁用注释可以插入到它自己的行中,将禁用应用于同一块中后面的所有内容。 Alternatively, it can be inserted at the end of the line for which it is meant to apply.或者,它可以插入到要应用的行的末尾。

If Pylint outputs " Locally disabling " messages, you can get rid of them by including the disable locally-disabled first as in the example above.如果 Pylint 输出“ Locally disabling disable”消息,您可以通过首先包含 disable locally-disabled来摆脱它们,如上例所示。

I had this problem using Eclipse and solved it as follows:我使用Eclipse遇到了这个问题,并解决了如下问题:

In the pylint folder (eg C:\Python26\Lib\site-packages\pylint ), hold Shift , right-click and choose to open the windows command in that folder.pylint 文件夹(例如C:\Python26\Lib\site-packages\pylint )中,按住Shift ,右键单击并选择在该文件夹中打开 windows 命令。 Type:类型:

lint.py --generate-rcfile > standard.rc

This creates the standard.rc configuration file.这将创建standard.rc配置文件。 Open it in Notepad and under [MESSAGES CONTROL] , uncomment disable= and add the message ID's you want to disable, eg:在记事本中打开它并在[MESSAGES CONTROL]下,取消注释disable=并添加您要禁用的消息 ID,例如:

disable=W0511, C0321

Save the file, and in Eclipse → WindowPreferencesPyDev → *pylint, in the arguments box, type:保存文件,然后在 Eclipse → WindowPreferencesPyDev → *pylint 中,在参数框中输入:

--rcfile=C:\Python26\Lib\site-packages\pylint\standard.rc

Now it should work...现在它应该工作...


You can also add a comment at the top of your code that will be interpreted by Pylint:您还可以在代码顶部添加将由 Pylint 解释的注释

# pylint: disable=C0321

Pylint message codes .皮林特消息代码


Adding eg --disable-ids=C0321 in the arguments box does not work.在参数框中添加例如--disable-ids=C0321不起作用。

All available Pylint messages are stored in the dictionary _messages , an attribute of an instance of the pylint.utils.MessagesHandlerMixIn class.所有可用的 Pylint 消息都存储在字典_messages中,它是pylint.utils.MessagesHandlerMixIn类实例的属性。 When running Pylint with the argument --disable-ids=... (at least without a configuration file), this dictionary is initially empty, raising a KeyError exception within Pylint ( pylint.utils.MessagesHandlerMixIn.check_message_id() .当使用参数--disable-ids=...运行 Pylint 时(至少没有配置文件),这个字典最初是空的,在 Pylint ( pylint.utils.MessagesHandlerMixIn.check_message_id()中引发 KeyError 异常。

In Eclipse, you can see this error-message in the Pylint Console (windows* → show viewConsole , select Pylint console from the console options besides the console icon.)在 Eclipse 中,您可以在 Pylint 控制台中看到此错误消息(windows* →显示视图控制台,从控制台图标旁边的控制台选项中选择 Pylint 控制台。)

To disable a warning locally in a block, add要在块中本地禁用警告,请添加

# pylint: disable=C0321

to that block.到那个街区。

There are several ways to disable warnings & errors from Pylint.有几种方法可以禁用 Pylint 的警告和错误。 Which one to use has to do with how globally or locally you want to apply the disablement -- an important design decision.使用哪一个与您希望在全球或本地应用禁用的方式有关——这是一个重要的设计决策。

Multiple Approaches多种方法

  1. In one or more pylintrc files.在一个或多个pylintrc文件中。

This involves more than the ~/.pylintrc file (in your $HOME directory) as described by Chris Morgan.这不仅仅涉及 Chris Morgan 所描述的~/.pylintrc文件(在您的 $HOME 目录中)。 Pylint will search for rc files, with a precedence that values "closer" files more highly: Pylint 将搜索 rc 文件,优先考虑“更接近”的文件:

  • A pylintrc file in the current working directory;当前工作目录中的一个pylintrc文件; or或者

  • If the current working directory is in a Python module (ie it contains an __init__.py file), searching up the hierarchy of Python modules until a pylintrc file is found;如果当前工作目录在 Python 模块中(即它包含一个__init__.py文件),则向上搜索 Python 模块的层次结构,直到找到一个pylintrc文件; or或者

  • The file named by the environment variable PYLINTRC;由环境变量 PYLINTRC 命名的文件; or或者

  • If you have a home directory that isn't /root :如果您的主目录不是/root

    • ~/.pylintrc ; ~/.pylintrc ; or或者

    • ~/.config/pylintrc ; ~/.config/pylintrc ; or或者

    • /etc/pylintrc

Note that most of these files are named pylintrc -- only the file in ~ has a leading dot.请注意,这些文件中的大多数都被命名为pylintrc —— 只有~中的文件有一个前导点。

To your pylintrc file, add lines to disable specific pylint messages.在您的pylintrc文件中,添加行以禁用特定的 pylint 消息。 For example:例如:

[MESSAGES CONTROL]
disable=locally-disabled
  1. Further disables from the pylint command line, as described by Aboo and Cairnarvon.如 Aboo 和 Cairnarvon 所述,从pylint命令行进一步禁用。 This looks like pylint --disable=bad-builtin .这看起来像pylint --disable=bad-builtin Repeat --disable to suppress additional items.重复--disable以抑制其他项目。

  2. Further disables from individual Python code lines, as described by Imolit.如 Imolit 所述,进一步禁用单个 Python 代码行。 These look like some statement # pylint: disable=broad-except (extra comment on the end of the original source line) and apply only to the current line .这些看起来像some statement # pylint: disable=broad-except (原始源代码行末尾的额外注释)并且仅适用于当前行 My approach is to always put these on the end of other lines of code so they won't be confused with the block style, see below.我的方法是始终将它们放在其他代码行的末尾,这样它们就不会与块样式混淆,见下文。

  3. Further disables defined for larger blocks of Python code, up to complete source files.为更大的 Python 代码块定义了进一步的禁用,直到完整的源文件。

    • These look like # pragma pylint: disable=bad-whitespace (note the pragma key word).这些看起来像# pragma pylint: disable=bad-whitespace (注意pragma关键字)。

    • These apply to every line after the pragma.这些适用于 pragma 之后的每一行 Putting a block of these at the top of a file makes the suppressions apply to the whole file.将其中的一个块放在文件的顶部会使抑制应用于整个文件。 Putting the same block lower in the file makes them apply only to lines following the block.将相同的块放在文件的较低位置使它们仅适用于该块之后的行。 My approach is to always put these on a line of their own so they won't be confused with the single-line style, see above.我的方法是始终将它们放在自己的一行上,这样它们就不会与单行样式混淆,见上文。

    • When a suppression should only apply within a span of code, use # pragma pylint: enable=bad-whitespace (now using enable not disable ) to stop suppressing.当抑制只适用于一段代码时,使用# pragma pylint: enable=bad-whitespace (现在使用enable not disable )停止抑制。

Note that disabling for a single line uses the # pylint syntax while disabling for this line onward uses the # pragma pylint syntax.请注意,禁用单行使用# pylint语法,而禁用此行以后使用# pragma pylint语法。 These are easy to confuse especially when copying & pasting.这些很容易混淆,尤其是在复制和粘贴时。

Putting It All Together把它们放在一起

I usually use a mix of these approaches.我通常混合使用这些方法。

  • I use ~/.pylintrc for absolutely global standards -- very few of these.我将~/.pylintrc用于绝对的全球标准——其中很少。

  • I use project-level pylintrc at different levels within Python modules when there are project-specific standards.当有特定于项目的标准时,我在 Python 模块中的不同级别使用项目级pylintrc Especially when you're taking in code from another person or team, you may find they use conventions that you don't prefer, but you don't want to rework the code.尤其是当您从其他人或团队接收代码时,您可能会发现他们使用了您不喜欢的约定,但您不想重新编写代码。 Keeping the settings at this level helps not spread those practices to other projects.将设置保持在此级别有助于不将这些做法传播到其他项目。

  • I use the block style pragmas at the top of single source files.我在单个源文件的顶部使用块样式编译指示。 I like to turn the pragmas off (stop suppressing messages) in the heat of development even for Pylint standards I don't agree with (like "too few public methods" -- I always get that warning on custom Exception classes) -- but it's helpful to see more / maybe all Pylint messages while you're developing.即使对于我不同意的 Pylint 标准(例如“公共方法太少”——我总是在自定义异常类上得到警告),我也喜欢在开发的热度中关闭编译指示(停止抑制消息)——但是在开发过程中查看更多/也许是所有 Pylint 消息会很有帮助。 That way you can find the cases you want to address with single-line pragmas (see below), or just add comments for the next developer to explain why that warning is OK in this case.这样你就可以找到你想用单行编译指示解决的情况(见下文),或者只是为下一个开发人员添加注释来解释为什么在这种情况下这个警告是可以的。

  • I leave some of the block-style pragmas enabled even when the code is ready to check in. I try to use few of those, but when it makes sense for the module, it's OK to do as documentation.即使代码准备好签入,我也会启用一些块式编译指示。我尝试使用其中的一些,但是当它对模块有意义时,可以作为文档来做。 However I try to leave as few on as possible, preferably none.但是我尽量少放,最好不要放。

  • I use the single-line-comment style to address especially potent errors.我使用单行注释样式来解决特别严重的错误。 For example, if there's a place where it actually makes sense to do except Exception as exc , I put the # pylint: disable=broad-except on that line instead of a more global approach because this is a strange exception and needs to be called out, basically as a form of documentation.例如,如果有一个地方实际上将except Exception as exc exc 是有意义的,我将# pylint: disable=broad-except放在该行而不是更全局的方法,因为这是一个奇怪的异常,需要调用出,基本上作为一种文档形式。


Like everything else in Python, you can act at different levels of indirection.与 Python 中的其他所有内容一样,您可以在不同的间接级别上执行操作。 My advice is to think about what belongs at what level so you don't end up with a too-lenient approach to Pylint.我的建议是考虑什么属于什么级别,这样你就不会对 Pylint 采取过于宽松的方法。

This is a FAQ :这是一个常见问题解答

4.1 Is it possible to locally disable a particular message? 4.1 是否可以在本地禁用特定消息?

Yes, this feature has been added in Pylint 0.11.是的,此功能已在 Pylint 0.11 中添加。 This may be done by adding # pylint: disable=some-message,another-one at the desired block level or at the end of the desired line of code.这可以通过在所需的块级别或所需代码行的末尾添加# pylint: disable=some-message,another-one来完成。

4.2 Is there a way to disable a message for a particular module only? 4.2 有没有办法只禁用特定模块的消息?

Yes, you can disable or enable (globally disabled) messages at the module level by adding the corresponding option in a comment at the top of the file:是的,您可以通过在文件顶部的注释中添加相应选项来在模块级别禁用或启用(全局禁用)消息:

 # pylint: disable=wildcard-import, method-hidden # pylint: enable=too-many-lines

You can disable messages by:您可以通过以下方式禁用消息:

  • numerical ID: E1101 , E1102 , etc.数字 ID: E1101E1102等。
  • symbolic message: no-member , undefined-variable , etc.符号信息: no-memberundefined-variable等。
  • the name of a group of checks.一组支票的名称。 You can grab those with pylint --list-groups .您可以使用pylint --list-groups来获取它们。
  • category of checks: C , R , W , etc.检查类别: CRW等。
  • all the checks with all . all 的all检查。

See the documentation (or run pylint --list-msgs in the terminal) for the full list of Pylint's messages.有关 Pylint 消息的完整列表,请参阅文档(或在终端中运行pylint --list-msgs )。 The documentation also provide a nice example of how to use this feature.该文档还提供了一个很好的示例来说明如何使用此功能。

You can also use the following command:您还可以使用以下命令:

pylint --disable=C0321  test.py

My Pylint version is 0.25.1.我的 Pylint 版本是 0.25.1。

You just have to add one line to disable what you want to disable.您只需添加一行即可禁用您要禁用的内容。

Eg,例如,

#pylint: disable = line-too-long, too-many-lines, no-name-in-module, import-error, multiple-imports, pointless-string-statement, wrong-import-order

Add this at the very beginning of your module.在模块的最开始添加它。

In case this helps someone, if you're using Visual Studio Code , it expects the file to be in UTF-8 encoding.如果这对某人有帮助,如果您使用的是Visual Studio Code ,它希望文件采用 UTF-8 编码。 To generate the file, I ran pylint --generate-rcfile | out-file -encoding utf8 .pylintrc为了生成文件,我运行了pylint --generate-rcfile | out-file -encoding utf8 .pylintrc pylint --generate-rcfile | out-file -encoding utf8 .pylintrc in PowerShell . pylint --generate-rcfile | out-file -encoding utf8 .pylintrc in PowerShell

Sorry for diverging a bit from the initial question, about poster's general preference, which would be better addressed by a global configuration file.很抱歉与最初的问题有所不同,关于海报的一般偏好,全局配置文件会更好地解决这个问题。 But, as in many popular answers, I tend to prefer seeing in my code what could trigger warnings , and eventually inform contributors as well.但是,就像在许多流行的答案中一样,我倾向于在我的代码中看到可能触发警告的内容,并最终通知贡献者
My comment to answer from @imolit needs to stay short, here are some details.我对@imolit 的回答需要简短,这里有一些细节。

For multiple-statements message, it's probably better to disable it at block or module level, like this对于multiple-statements消息,最好在块或模块级别禁用它,如下所示

# pylint: disable=multiple-statements

My use-case being now attribute-defined-outside-init in a unittest setup(), I opted for a line-scoped message disabling, using the message code to avoid the line-too-long issue.我的用例现在是 unittest setup() 中的attribute-defined-outside-init ,我选择了行范围的消息禁用,使用消息代码来避免line-too-long问题。

class ParserTest(unittest.TestCase):
   def setUp(self):
       self.parser = create_parser()  # pylint: disable=W0201

The correspondance can be found locally with a command like可以使用以下命令在本地找到对应关系

$ pylint --list-msgs | grep 'outside-init'
:attribute-defined-outside-init (W0201): *Attribute %r defined outside __init__*

Of course, you would similarly retrieve the symbolic name from the code.当然,您可以类似地从代码中检索符号名称。

As per Pylint documentation, the easiest is to use this chart :根据Pylint文档,最简单的方法是使用此图表

  • C convention-related checks C 约定相关的检查
  • R refactoring-related checks R 重构相关检查
  • W various warnings W 各种警告
  • E errors, for probable bugs in the code E 错误,用于代码中可能的错误
  • F fatal, if an error occurred which prevented Pylint from doing further processing. F 致命,如果发生错误导致 Pylint 无法进行进一步处理。

So one can use:所以可以使用:

pylint -j 0 --disable=I,E,R,W,C,F YOUR_FILES_LOC

Python syntax does permit more than one statement on a line, separated by semicolon (;). Python 语法允许在一行中有多个语句,用分号 (;) 分隔。 However, limiting each line to one statement makes it easier for a human to follow a program's logic when reading through it.但是,将每一行限制为一个语句可以使人们在阅读程序时更容易遵循程序的逻辑。

So, another way of solving this issue, is to understand why the lint message is there and not put more than one statement on a line.因此,解决此问题的另一种方法是了解为什么存在 lint 消息并且不在一行中放置多个语句。

Yes, you may find it easier to write multiple statements per line, however, Pylint is for every other reader of your code not just you.是的,您可能会发现每行编写多个语句更容易,但是,Pylint 不仅适用于您的代码的所有其他读者。

My pylint kept ignoring the disable list in my .pylintrc .我的 pylint 一直忽略我的pylint .pylintrcdisable列表。 Finally, I realized that I was executing:最后,我意识到我正在执行:

pylint --disable=all --enable=F,E,W

which was overriding the disable list in my .pylintrc .它覆盖了我的.pylintrc中的disable列表。

The correct command to show only Fatal, Errors, Warnings, is:仅显示致命、错误、警告的正确命令是:

pylint --disable=C,R

Edit "C:\Users\Your User\AppData\Roaming\Code\User\settings.json" and add 'python.linting.pylintArgs' with its lines at the end as shown below:编辑“C:\Users\Your User\AppData\Roaming\Code\User\settings.json”并在末尾添加“python.linting.pylintArgs”及其行,如下所示:

{
    "team.showWelcomeMessage": false,
    "python.dataScience.sendSelectionToInteractiveWindow": true,
    "git.enableSmartCommit": true,
    "powershell.codeFormatting.useCorrectCasing": true,
    "files.autoSave": "onWindowChange",
    "python.linting.pylintArgs": [
        "--load-plugins=pylint_django",
        "--errors-only"
    ],
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM