如何禁用 Pylint 警告?

发布于 2024-10-05 22:58:21 字数 416 浏览 6 评论 0原文

我试图在 Pylint 0.21.1 中禁用警告 C0321(“单行上有多个语句”——我经常将带有短单行结果的 if 语句放在同一行上) (如果重要的话:astng 0.20.1、common 0.50.3 和 Python 2.6.6(r266:84292,2010 年 9 月 15 日,16:22:56))。

我尝试在 Pylint 配置文件中添加 disable=C0321,但 Pylint 仍然坚持报告它。该行的变体(例如 disable=0321disable=C321)被标记为错误,因此 Pylint 确实正确识别该选项。它只是忽略它。

这是 Pylint 错误,还是我做错了什么?有办法解决这个问题吗?

我真的很想摆脱一些噪音。

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)).

I've tried adding disable=C0321 in the Pylint configuration file, but Pylint insists on reporting it anyway. Variations on that line (like disable=0321 or disable=C321) are flagged as errors, so Pylint does recognize the option properly. It's just ignoring it.

Is this a Pylint bug, or am I doing something wrong? Is there a way around this?

I'd really like to get rid of some of this noise.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

ζ澈沫 2024-10-12 22:58:21

从 Pylint v. 0.25.3 开始,您可以使用符号名称来禁用警告 而不必记住所有这些代码。例如:

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

这种风格比神秘的错误代码更具启发性,也更实用,因为较新版本的 Pylint 只输出符号名称,而不输出错误代码。

可以在其自己的行上插入禁用注释,将禁用应用于同一块中后面的所有内容。或者,可以将其插入到要应用的行的末尾。

如果 Pylint 输出“Locally disabling”消息,您可以通过包含 locally-disabled first 来消除它们,如上例所示。

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. E.g.:

# 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.

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.

守望孤独 2024-10-12 22:58:21

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=

所以看起来你的 ~/.pylintrc 应该有 disable= 行它位于[MESSAGES CONTROL]部分内。

pylint --generate-rcfile shows it like this:

[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].

温柔女人霸气范 2024-10-12 22:58:21

我使用 Eclipse 遇到了这个问题,并按如下方式解决:

pylint 文件夹 中(例如 C:\Python26\Lib\site-packages\pylint),按住 Shift,右键单击并选择打开该文件夹中的 windows 命令。类型:

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

这将创建 standard.rc 配置文件。在记事本中打开它,然后在 [MESSAGES CONTROL] 下取消注释
disable= 并添加您要禁用的消息 ID,例如:

disable=W0511, C0321

保存文件,然后在 Eclipse → WindowPreferencesPyDev → *pylint,在参数框中,键入:

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

现在它应该可以工作...


您还可以在代码顶部添加注释,该注释将由 Pylint 解释:

# pylint: disable=C0321

< strong>Pylint 消息代码


在参数框中添加例如 --disable-ids=C0321 不起作用。

所有可用的 Pylint 消息都存储在字典 _messages 中,它是 pylint.utils.MessagesHandlerMixIn 类实例的属性。当使用参数 --disable-ids=... 运行 Pylint 时(至少没有配置文件),该字典最初为空,在 Pylint 中引发 KeyError 异常(pylint.utils .MessagesHandlerMixIn.check_message_id()

在 Eclipse 中,您可以在 Pylint 控制台中看到此错误消息(Windows* → 显示视图控制台,选择 Pylint除了控制台图标之外,还可以从控制台选项中获取控制台。)

I had this problem using Eclipse and solved it as follows:

In the pylint folder (e.g. C:\Python26\Lib\site-packages\pylint), hold Shift, right-click and choose to open the windows command in that folder. Type:

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

This creates the standard.rc configuration file. Open it in Notepad and under [MESSAGES CONTROL], uncomment
disable= and add the message ID's you want to disable, e.g.:

disable=W0511, C0321

Save the file, and in Eclipse → WindowPreferencesPyDev → *pylint, in the arguments box, type:

--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: disable=C0321

Pylint message codes.


Adding e.g. --disable-ids=C0321 in the arguments box does not work.

All available Pylint messages are stored in the dictionary _messages, an attribute of an instance of the pylint.utils.MessagesHandlerMixIn class. 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().

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.)

公布 2024-10-12 22:58:21

要在块中本地禁用警告,请添加

# pylint: disable=C0321

到该块。

To disable a warning locally in a block, add

# pylint: disable=C0321

to that block.

山色无中 2024-10-12 22:58:21

有多种方法可以禁用警告和警告。来自 Pylint 的错误。使用哪一个与您想要在全局或本地应用禁用的方式有关——这是一项重要的设计决策。

多种方法

  1. 在一个或多个 pylintrc 文件中。

这不仅仅涉及 Chris Morgan 所描述的 ~/.pylintrc 文件(在您的 $HOME 目录中)。 Pylint 将搜索 rc 文件,并优先考虑“更接近”的文件:

  • 当前工作目录中的

    A pylintrc 文件;或

  • 如果当前工作目录位于 Python 模块中(即包含 __init__.py 文件),则向上搜索 Python 模块的层次结构,直到出现 pylintrc 文件被发现;或

  • 环境变量 PYLINTRC 命名的文件;或

  • 如果您的主目录不是/root

    • ~/.pylintrc;或

    • ~/.config/pylintrc;或

    • /etc/pylintrc

请注意,大多数这些文件都被命名为 pylintrc ——只有~ 中的文件有一个前导点。

在您的 pylintrc 文件中,添加行以禁用特定的 pylint 消息。例如:

[MESSAGES CONTROL]
disable=locally-disabled
  1. pylint 命令行进一步禁用,如 Aboo 和 Cairnarvon 所描述。这看起来像pylint --disable=bad-builtin。重复 --disable 以抑制其他项目。

  2. 进一步禁用单个 Python 代码行,如 Imolit 所描述。这些看起来像一些语句 # pylint:disable=broad- except(原始源代码行末尾的额外注释)并且仅应用于当前行。我的方法是始终将它们放在其他代码行的末尾,这样它们就不会与块样式混淆,请参见下文。

  3. 进一步禁用更大的 Python 代码块的定义,直至完整的源文件。

    • 这些看起来像# pragma pylint:disable=bad-whitespace(注意pragma关键字)。

    • 这些适用于编译指示之后的每一行。将这些块放在文件顶部会使抑制应用于整个文件。将相同的块放在文件的较低位置使它们仅适用于该块后面的行。我的方法是始终将它们放在自己的一行中,这样它们就不会与单行样式混淆,请参见上文。

    • 当抑制仅应在代码范围内应用时,请使用# pragma pylint:enable=bad-whitespace(现在使用enable而不是禁用)以停止抑制。

请注意,禁用单行使用 # pylint 语法,而禁用此行之后使用 # pragma pylint 语法。这些很容易混淆,尤其是在复制和复制时。粘贴。

综合起来

我通常会混合使用这些方法。

  • 我使用~/.pylintrc作为绝对全球标准——很少。

  • 当存在特定于项目的标准时,我在 Python 模块中的不同级别使用项目级 pylintrc。特别是当您从其他人或团队获取代码时,您可能会发现他们使用您不喜欢的约定,但您不想重新编写代码。将设置保留在此级别有助于不将这些实践传播到其他项目。

  • 我在单个源文件的顶部使用块样式编译指示。我喜欢在开发热潮中关闭编译指示(停止抑制消息),即使对于我不同意的 Pylint 标准(例如“公共方法太少”——我总是在自定义异常类上收到该警告)——但是在开发过程中查看更多/也许所有 Pylint 消息会很有帮助。这样你就可以找到你想要用单行编译指示解决的情况(见下文),或者只是为下一个开发人员添加注释来解释为什么在这种情况下警告是可以的。

  • 即使代码已准备好签入,我也会启用一些块样式的编译指示。我尝试使用其中的一些,但当它对模块有意义时,可以将其作为文档。不过,我尝试保留尽可能少的内容,最好不保留。

  • 我使用单行注释风格来解决特别严重的错误。例如,如果某个地方执行 except Exception as exc 确实有意义,我会将 # pylint:disable=broad- except 放在该行上,而不是更全局的方法,因为这是一个奇怪的异常,需要被调用,基本上作为文档的一种形式。


与 Python 中的其他内容一样,您可以在不同的间接级别上进行操作。我的建议是考虑一下什么属于什么级别,这样你就不会最终对 Pylint 采取过于宽松的方法。

There are several ways to disable warnings & errors from 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.

This involves more than the ~/.pylintrc file (in your $HOME directory) as described by Chris Morgan. Pylint will search for rc files, with a precedence that values "closer" files more highly:

  • A pylintrc file in the current working directory; or

  • If the current working directory is in a Python module (i.e. it contains an __init__.py file), searching up the hierarchy of Python modules until a pylintrc file is found; or

  • The file named by the environment variable PYLINTRC; or

  • If you have a home directory that isn’t /root:

    • ~/.pylintrc; or

    • ~/.config/pylintrc; or

    • /etc/pylintrc

Note that most of these files are named pylintrc -- only the file in ~ has a leading dot.

To your pylintrc file, add lines to disable specific pylint messages. For example:

[MESSAGES CONTROL]
disable=locally-disabled
  1. Further disables from the pylint command line, as described by Aboo and Cairnarvon. This looks like pylint --disable=bad-builtin. Repeat --disable to suppress additional items.

  2. Further disables from individual Python code lines, as described by Imolit. 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. 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.

    • These look like # pragma pylint: disable=bad-whitespace (note the pragma key word).

    • These apply to every line after the 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.

Note that disabling for a single line uses the # pylint syntax while disabling for this line onward uses the # pragma pylint syntax. 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.

  • I use project-level pylintrc at different levels within Python modules when there are project-specific standards. 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. 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.


Like everything else in Python, you can act at different levels of indirection. My advice is to think about what belongs at what level so you don't end up with a too-lenient approach to Pylint.

孤千羽 2024-10-12 22:58:21

这是常见问题解答

4.1 是否可以在本地禁用特定消息?

是的,Pylint 0.11 中已添加此功能。这可以通过以下方式完成
添加
# pylint: 在所需位置禁用=some-message,another-one
块级或所需代码行的末尾。

4.2 有没有办法仅禁用特定模块的消息?

是的,您可以在以下位置禁用或启用(全局禁用)消息:
模块级别通过在注释中添加相应的选项
文件顶部:

# pylint:disable=通配符导入,方法隐藏
# pylint: 启用=太多行

您可以通过以下方式禁用消息:

  • 数字 ID:E1101E1102
  • 符号消息:no-memberundefined-variable
  • 一组检查的名称。您可以使用 pylint --list-groups 获取这些内容。
  • 检查类别:CRW等。
  • 所有检查均带有all

请参阅文档(或运行pylint --list-msgs 在终端中)以获取 Pylint 消息的完整列表。该文档还提供了一个很好的示例,说明如何使用此功能。

This is a FAQ:

4.1 Is it possible to locally disable a particular message?

Yes, this feature has been added in 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.

4.2 Is there a way to disable a message for a particular module only?

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.
  • symbolic message: no-member, undefined-variable, etc.
  • the name of a group of checks. You can grab those with pylint --list-groups.
  • category of checks: C, R, W, etc.
  • all the checks with all.

See the documentation (or run pylint --list-msgs in the terminal) for the full list of Pylint's messages. The documentation also provide a nice example of how to use this feature.

酒绊 2024-10-12 22:58:21

还可以使用以下命令:

pylint --disable=C0321  test.py

我的Pylint版本是0.25.1。

You can also use the following command:

pylint --disable=C0321  test.py

My Pylint version is 0.25.1.

乱了心跳 2024-10-12 22:58:21

您只需添加一行即可禁用您想要禁用的内容。

例如,

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

将其添加到模块的最开头。

You just have to add one line to disable what you want to disable.

E.g.,

#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.

天荒地未老 2024-10-12 22:58:21

如果这对某人有帮助,如果您使用 Visual Studio Code,它期望该文件采用 UTF-8 编码。为了生成该文件,我运行了 pylint --generate-rcfile | PowerShell 中的 out-file -encoding utf8 .pylintrc。

In case this helps someone, if you're using Visual Studio Code, it expects the file to be in UTF-8 encoding. To generate the file, I ran pylint --generate-rcfile | out-file -encoding utf8 .pylintrc in PowerShell.

錯遇了你 2024-10-12 22:58:21

抱歉,与最初的问题有所不同,关于发布者的一般偏好,这可以通过全局配置文件更好地解决。
但是,正如许多流行的答案一样,我倾向于在我的代码中查看什么可能会触发警告,并最终通知贡献者
我对@imolit的回答的评论需要保持简短,这里有一些细节。

对于多个-statements 消息,最好在块或模块级别禁用它,就像这样

# pylint: disable=multiple-statements

我的用例现在是 attribute-defined-outside-init 中在单元测试 setup() 中,我选择禁用行范围消息,使用消息代码来避免行太长问题。

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

可以使用类似的命令在本地找到对应关系,

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

当然,您也可以类似地从代码中检索符号名称。

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.

For multiple-statements message, it's probably better to disable it at block or module level, like this

# 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.

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.

纸短情长 2024-10-12 22:58:21

根据 Pylint 文档,最简单的方法是使用 此图表

  • C 约定相关的检查
  • R 重构相关的检查
  • W 各种警告
  • E 错误,代码中可能存在的错误
  • F 致命的,如果发生阻止 Pylint 进行进一步处理的错误。

所以人们可以使用:

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

As per Pylint documentation, the easiest is to use this chart:

  • C convention-related checks
  • R refactoring-related checks
  • W various warnings
  • E errors, for probable bugs in the code
  • F fatal, if an error occurred which prevented Pylint from doing further processing.

So one can use:

pylint -j 0 --disable=I,E,R,W,C,F YOUR_FILES_LOC
回心转意 2024-10-12 22:58:21

在下一行禁用

除了其他答案之外:您还可以使用 disable-next 禁用下一行的通知,这可以派上用场,例如对于函数定义或一般的长行:

# pylint: disable-next=dangerous-default-value
def find_zeros(my_list = []):
    sum = 0
    for element in list:
        if element == 0:
            sum += 1
    return sum

Disable in next line

In addition to the other answers: You can also disable notifications for the next line with disable-next This can come in handy for example for function definitions, or long lines in general:

# pylint: disable-next=dangerous-default-value
def find_zeros(my_list = []):
    sum = 0
    for element in list:
        if element == 0:
            sum += 1
    return sum
原来分手还会想你 2024-10-12 22:58:21

Python 语法允许一行上有多个语句,并用分号 (;) 分隔。然而,将每一行限制为一个语句可以使人们在阅读程序时更容易遵循程序的逻辑。

因此,解决此问题的另一种方法是了解为什么存在 lint 消息,并且不要在一行上放置多个语句。

是的,您可能会发现每行编写多个语句更容易,但是,Pylint 适合您代码的所有其他读者,而不仅仅是您。

Python syntax does permit more than one statement on a line, separated by semicolon (;). 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.

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.

鼻尖触碰 2024-10-12 22:58:21

我的 pylint 一直忽略 .pylintrc 中的 disable 列表。最后,我意识到我正在执行:

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

它覆盖了我的 .pylintrc 中的 disable 列表。

仅显示致命、错误、警告的正确命令是:

pylint --disable=C,R

My pylint kept ignoring the disable list in my .pylintrc. Finally, I realized that I was executing:

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

which was overriding the disable list in my .pylintrc.

The correct command to show only Fatal, Errors, Warnings, is:

pylint --disable=C,R
紫竹語嫣☆ 2024-10-12 22:58:21

编辑“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"
    ],
}

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:

{
    "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"
    ],
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文