ChatGPT解决这个技术问题 Extra ChatGPT

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

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.

There is a good solution here if you want to disable a single line of code, not all errors of a kind.

C
Chris Morgan

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


Thanks, but it already does, in the [MESSAGES CONTROL] section as shown above. Still ignored.
@Head Geek: well, it works for me. ~/.pylintrc with two lines, [MESSAGES CONTROL] and disable=C0321. That prevents that message.
Odd... the exact same version of PyLint?
@Head Geek: 0.21.3, astng 0.20.3 and common 0.52.1 actually (the latest when I installed it, more recent than yours)
If you want to have a project specific pylintrc, make sure to name it pylintrc otherwise the location will need to be specifically stated.
P
Peter Mortensen

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.

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.


But putting # pylint: disable=foo inlyne makes me line too long, so now I need to add , line-too-long! Tongue-in-cheek; this was what I needed and solves my issue. Thanks!
We might diverge here from the initial question, about general user preference, hence would be better addressed by a global configuration file. As I prefer seeing in my code what could trigger warnings, for my current use-case, I opted for a line-scoped message disabling, using the message code to avoid the line-too-long issue. The correspondance can be found locally with a command like pylint --list-msgs | grep <code or keyword> See my answer for details, as a comment needs too stay short.
The link provided by @omni is dead. You can type pylint --list-msgs to list all strings
P
Peter Mortensen

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 → Window → Preferences → PyDev → *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 view → Console, select Pylint console from the console options besides the console icon.)


No, it really shouldn't. 1) It references Eclipse, which is irrelevant to the question asked 2) It recommends disabling through the legacy message codes. I would recommend my answer for the simplest solution to the problem, or Chris Johnson's answer for more details.
-1 Creating a global configuration file is harmful as it will impact all users of the system. If anything this should be a per-user configuration file, or even better, a project specific configuration file.
t
thakis

To disable a warning locally in a block, add

# pylint: disable=C0321

to that block.


This is a legacy technique and is no longer recommended. See the other answers.
You mean one should use the symbolic name instead of the code number, yes?
Yes. The answer by imolit covers exactly this.
How does one find the symbolic name? My editor will spit out [pylint] C0111: Missing method docstring, so finding the code number is easy, but finding the symbolic name means I have to look it up.
Note that Visual Studio Code is now displaying the symbolic name instead of error code.
A
Asclepius

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

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

~/.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

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


For the most part I cannot advocate using a global nonempty ~/.pylintrc. IMHO, the configuration should typically be tied to the project, and so it must be somewhere within the project. Only then can it be version controlled and shared with the project. Failing this, a clone may lack the customizations necessary for pylint to exit without printing messages.
@ChrisJohnson The prefix pragma seems totally unnecessary. For example, I have # pylint: disable=missing-docstring in the top of my file, and it applies to the entire remainder of the file. Please check and remove the pragma prefix from your answer.
Pylint FAQ doesn't write about any pragma. (pylint.pycqa.org/en/latest/…): 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
Pragma is discussed in the “Messages control” section of that documentation.
@ChrisJohnson, the # pylint: ... comments are called pragmas, but there is no need to write # pragma pylint. The word pragma does not have any special meaning In Python like it does in C/C++. I think this is confusing in your answer and hope you will update it. For the rest: great answer 👍
P
Peter Mortensen

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.


P
Peter Mortensen

You can also use the following command:

pylint --disable=C0321  test.py

My Pylint version is 0.25.1.


This is now a legacy technique. Use of the symbolic name of the disabled warning is recommended instead. See this answer.
This doesn't seem to work with the --py3k flag either :(
Interestingly enough, it works fine if supplied in the rc file, and (more troubling) it actually generates a correct rc file with --generate-rcfile. Gotta love code with multiple branches that do the same thing :(
P
Peter Mortensen

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.


Or in front of the line who is generating the message if you don't want to generalize.
P
Peter Mortensen

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.


R
RockyRoad

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.


P
Peter Mortensen

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

P
Peter Mortensen

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.


w
wisbucky

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

a
aarw76

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