Technical Documentation: pylint-dev/pylint
โน๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference
Doc Contact (`doc/contact.rst`)
Contact
Bug reports, feedback
.. _bug reports, feedback:
You think you have found a bug in Pylint? Well, this may be the case
since Pylint and Python are under heavy development!
Please take the time to check if it is already in the issue tracker at
https://github.com/pylint-dev/pylint
Note that the issue might also be reported in one of Pylint's major dependencies,
astroid:
Discord server
You can discuss your problem using the discord server:
https://discord.com/invite/Egy6P8AMB5
Mailing lists
.. _Mailing lists:
The code-quality mailing list is shared with other tools that aim
at improving the quality of python code.
You can subscribe to this mailing list at
https://mail.python.org/mailman3/lists/code-quality.python.org/
Archives are available at
https://mail.python.org/pipermail/code-quality/
Archives before April 2013 are not available anymore. At
https://mail.python.org/pipermail/ it was under python-projects.
Support
.. image:: media/Tidelift_Logos_RGB_Tidelift_Shorthand_On-White.png
:height: 150
:alt: Tidelift
:align: left
:class: tideliftlogo
Professional support for pylint is available as part of the Tidelift Subscription_. Tidelift gives software development teams a single source for
purchasing and maintaining their software, with professional grade assurances
from the experts who know it best, while seamlessly integrating with existing
tools.
.. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-pylint?utm_source=pypi-pylint&utm_medium=referral&utm_campaign=readme
Doc Faq (`doc/faq.rst`)
.. _faq:
========================== Frequently Asked Questions
How do I install Pylint?
.. include:: short_text_installation.rst
How do I contribute to Pylint?
.. include:: short_text_contribute.rst
Does Pylint follow a versioning scheme?
See :ref:upgrading pylint in the installation guide .
How do I find the name corresponding to a specific command line option?
See :ref:the configuration documentation <all-configurations-options>.
What is the format of the configuration file?
The configuration file can be an ini or toml file. See the :ref:exhaustive list of possible options <all-options>.
How to disable a particular message?
Read :ref:message-control for details and examples.
Pylint gave my code a negative rating out of ten. That can't be right!
Prior to Pylint 2.13.0, the score formula used by default had no lower
bound. The new default score formula is ::
max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))If your project contains a configuration file created by an earlier version of
Pylint, you can set evaluation to the above expression to get the new
behavior. Likewise, since negative values are still technically supported,evaluation can be set to a version of the above expression that does not
enforce a floor of zero.
How do I avoid getting unused argument warnings for API I do not control?
Prefix (ui) the callback's name by cb_ (callback), as in cb_onclick(...). By
doing so arguments usage won't be checked. Another solution is to
use one of the names defined in the "dummy-variables" configuration
variable for unused argument ("_" and "dummy" by default).
Why are there a bunch of messages disabled by default?
Either because they are prone to false positives or that they are opinionated enough
to not be included as default messages.
You can see the plugin you need to explicitly :ref:load in the technical reference .
I want to run pylint on each keystroke in my IDE. How do I do that?
Pylint full suite of checks will never be fast enough to run on every keystroke.
However, some IDEs can run pylint when the IDE opens or saves files.
See, for example, the Microsoft plugin for VS Code_.
That said, pylint is best suited for linting on save for small projects, for continuous
integration jobs, or a git pre-push hook for big projects. The larger your repository
is, the slower pylint will be.
If you want to make pylint faster for this type of use case, you can use the --errors-only
option, which will remove all the refactor, convention, and warning checks. You can also disable
checks with inherently high complexity that need to analyse the full code base likeduplicate-code or cyclic-import (this list is not exhaustive).
.. _Microsoft plugin for VS Code: https://github.com/microsoft/vscode-pylint#readme
Why do I have non-deterministic results when I try to parallelize pylint ?
pylint should analyse all your code at once in order to best infer the
actual values that result from calls. If only some of the files are given, pylint might
miss a particular value's type and produce inferior inference for the subset. Parallelization
of pylint is not easy; we also discourage the use of the -j option if this matters to you.
Which messages should I disable to avoid duplicates if I use other popular linters ?
pycodestyle_: bad-indentation, bare-except, line-too-long, missing-final-newline, multiple-statements, singleton-comparison, trailing-newlines, trailing-whitespace, unnecessary-negation, unnecessary-semicolon, wrong-import-position
pyflakes_: undefined-variable, unused-import, unused-variable
mccabe_: too-many-branches
pydocstyle_: missing-module-docstring, missing-class-docstring, missing-function-docstring
pep8-naming_: invalid-name, bad-classmethod-argument, bad-mcs-classmethod-argument, no-self-argument
isort_ and flake8-import-order_: ungrouped-imports, wrong-import-order
.. _pycodestyle: https://github.com/PyCQA/pycodestyle
.. _pyflakes: https://github.com/PyCQA/pyflakes
.. _mccabe: https://github.com/PyCQA/mccabe
.. _pydocstyle: https://github.com/PyCQA/pydocstyle
.. _pep8-naming: https://github.com/PyCQA/pep8-naming
.. _isort: https://github.com/pycqa/isort
.. _flake8-import-order: https://github.com/PyCQA/flake8-import-order
How do I avoid "access to undefined member" messages in my mixin classes?
You should add the no-member message to your ignored-checks-for-mixins option
and name your mixin class with a name which ends with "Mixin" or "mixin" (default)
or change the default value by changing the mixin-class-rgx option.
Where is the persistent data stored to compare between successive runs?
Analysis data are stored as a pickle file in a directory which is
localized using the following rules:
- value of the PYLINTHOME environment variable if set
- "pylint" subdirectory of the user's XDG_CACHE_HOME if the environment variable is set, otherwise
- Linux: "~/.cache/pylint"
- macOS: "~/Library/Caches/pylint"
- Windows: "C:\Users\\AppData\Local\pylint"
- ".pylint.d" directory in the current directory
How does the website pylint dot org relate to this project?
Historically, pylint dot org served as the primary website for Pylint. However,
we no longer have access to the domain. The current owners are monetizing
this by displaying advertisements alongside outdated documentation without
contributing to pylint at all. For the latest and official Pylint documentation,
please visit pylint.readthedocs.io <https://pylint.readthedocs.io/en/stable/>_.
Please see issue 8934 <https://github.com/pylint-dev/pylint/issues/8934>_
for more details.
Doc Index (`doc/index.rst`)
.. include:: ../README.rst
.. toctree::
:titlesonly:
:hidden:
tutorial
.. toctree::
:caption: User Guide
:titlesonly:
:hidden:
user_guide/installation/index
user_guide/usage/index
user_guide/messages/index
user_guide/configuration/index
user_guide/checkers/index
.. toctree::
:caption: Developer Guide
:maxdepth: 2
:titlesonly:
:hidden:
development_guide/api/index
development_guide/how_tos/index.rst
development_guide/technical_reference/index.rst
development_guide/contributor_guide/index
.. toctree::
:caption: Additional tools
:maxdepth: 3
:titlesonly:
:hidden:
additional_tools/pyreverse/index
additional_tools/symilar/index
.. toctree::
:caption: Changelog
:titlesonly:
:hidden:
whatsnew/index.rst
.. toctree::
:caption: Support
:titlesonly:
:hidden:
faq
contact
Doc Requirements (`doc/requirements.txt`)
Sphinx==9.0.4
sphinx-reredirects<2
towncrier>=24.8,<27.0
furo==2025.12.19
Doc Short Text Contribute (`doc/short_text_contribute.rst`)
.. include:: ../README.rst
:start-after: This is used inside the doc to recover the start of the short text for contribution
:end-before: This is used inside the doc to recover the end of the short text for contribution
Doc Short Text Installation (`doc/short_text_installation.rst`)
.. include:: ../README.rst
:start-after: This is used inside the doc to recover the start of the short text for installation
:end-before: This is used inside the doc to recover the end of the short text for installation
Doc Tutorial (`doc/tutorial.rst`)
.. _tutorial:
======== Tutorial
This tutorial is all about approaching coding standards with little or no
knowledge of in-depth programming or the code standards themselves. It's the
equivalent of skipping the manual and jumping right in.
The command line prompt for these examples is:
.. sourcecode:: console
tutor Desktop$
.. _PEP 8: https://peps.python.org/pep-0008/
Getting Started
Running Pylint with the --help arguments will give you an idea of the arguments
available. Do that now, i.e.:
.. sourcecode:: console
pylint --help
A couple of the options that we'll focus on here are: ::
Commands:
--help-msg=
--generate-toml-config
Messages control:
--disable=
Reports:
--reports=
--output-format=
If you need more detail, you can also ask for an even longer help message: ::
pylint --long-help
Pay attention to the last bit of this longer help output. This gives you a
hint of what Pylint is going to pick on: ::
Output:
Using the default text output, the message format is :
MESSAGE_TYPE: LINE_NUM:[OBJECT:] MESSAGE
There are 5 kind of message types :
* (C) convention, for programming standard violation
* (R) refactor, for bad code smell
* (W) warning, for python specific problems
* (E) error, for probable bugs in the code
* (F) fatal, if an error occurred which prevented pylint from doing
further processing.
When Pylint is first run on a fresh piece of code, a common complaint is that it
is too noisy. The default configuration enforce a lot of warnings.
We'll use some of the options we noted above to make it suit your
preferences a bit better.
Your First Pylint'ing
We'll use a basic Python script with black_ already applied on it,
as fodder for our tutorial. The starting code we will use is calledsimplecaesar.py and is here in its entirety:
.. _black: https://github.com/psf/black
.. sourcecode:: python
#!/usr/bin/env python3
import string
shift = 3
choice = input("would you like to encode or decode?")
word = input("Please enter text")
letters = string.ascii_letters + string.punctuation + string.digits
encoded = ""
if choice == "encode":
for letter in word:
if letter == " ":
encoded = encoded + " "
else:
x = letters.index(letter) + shift
encoded = encoded + letters[x]
if choice == "decode":
for letter in word:
if letter == " ":
encoded = encoded + " "
else:
x = letters.index(letter) - shift
encoded = encoded + letters[x]
print(encoded)Let's get started. If we run this:
.. sourcecode:: console
tutor Desktop$ pylint simplecaesar.py
************* Module simplecaesar
simplecaesar.py:1:0: C0114: Missing module docstring (missing-module-docstring)
simplecaesar.py:5:0: C0103: Constant name "shift" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:8:0: C0103: Constant name "letters" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:9:0: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:13:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:15:12: C0103: Constant name "x" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:16:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:20:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:22:12: C0103: Constant name "x" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:23:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)
-----------------------------------
Your code has been rated at 4.74/10We can see the second line is: ::
"simplecaesar.py:1:0: C0114: Missing module docstring (missing-module-docstring)"
This basically means that line 1 at column 0 violates the convention C0114.
Another piece of information is the message symbol between parens,missing-module-docstring.
If we want to read up a bit more about that, we can go back to the
command line and try this:
.. sourcecode:: console
tutor Desktop$ pylint --help-msg=missing-module-docstring
:missing-module-docstring (C0114): Missing module docstring
Used when a module has no docstring.Empty modules do not require a docstring.
This message belongs to the basic checker.
That one was a bit of a no-brainer, but we can also run into error messages
where we are unfamiliar with the underlying code theory.
The Next Step
Now that we got some configuration stuff out of the way, let's see what we can
do with the remaining warnings. If we add a docstring to describe what the code
is meant to do that will help. There are invalid-name messages that we will
get to later. Here is the updated code:
.. sourcecode:: python
#!/usr/bin/env python3
"""This script prompts a user to enter a message to encode or decode
using a classic Caesar shift substitution (3 letter shift)"""
import string
shift = 3
choice = input("would you like to encode or decode?")
word = input("Please enter text")
letters = string.ascii_letters + string.punctuation + string.digits
encoded = ""
if choice == "encode":
for letter in word:
if letter == " ":
encoded = encoded + " "
else:
x = letters.index(letter) + shift
encoded = encoded + letters[x]
if choice == "decode":
for letter in word:
if letter == " ":
encoded = encoded + " "
else:
x = letters.index(letter) - shift
encoded = encoded + letters[x]
print(encoded)Here is what happens when we run it:
.. sourcecode:: console
tutor Desktop$ pylint simplecaesar.py
************* Module simplecaesar
simplecaesar.py:8:0: C0103: Constant name "shift" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:11:0: C0103: Constant name "letters" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:12:0: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:16:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:18:12: C0103: Constant name "x" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:19:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:23:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:25:12: C0103: Constant name "x" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:26:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)
------------------------------------------------------------------
Your code has been rated at 5.26/10 (previous run: 4.74/10, +0.53)Nice! Pylint told us how much our code rating has improved since our last run,
and we're down to just the invalid-name messages.
There are fairly well defined conventions around naming things like instance
variables, functions, classes, etc. The conventions focus on the use of
UPPERCASE and lowercase as well as the characters that separate multiple words
in the name. This lends itself well to checking via a regular expression, thus
the should match (([A-Z_][A-Z1-9_]*)|(.*))$.
In this case Pylint is telling us that those variables appear to be constants
and should be all UPPERCASE. This is an in-house convention that has lived with Pylint
since its inception. You too can create your own in-house naming
conventions but for the purpose of this tutorial, we want to stick to the PEP 8_
standard. In this case, the variables we declared should follow the convention
of all lowercase. The appropriate rule would be something like:
"should match [a-z_][a-z0-9_]{2,30}$". Notice the lowercase letters in the
regular expression (a-z versus A-Z).
If we run that rule using a --const-rgx='[a-z\_][a-z0-9\_]{2,30}$' option, it
will now be quite quiet:
.. sourcecode:: console
tutor Desktop$ pylint simplecaesar.py --const-rgx='[a-z\_][a-z0-9\_]{2,30}$'
************* Module simplecaesar
simplecaesar.py:18:12: C0103: Constant name "x" doesn't conform to '[a-z\\_][a-z0-9\\_]{2,30}$' pattern (invalid-name)
simplecaesar.py:25:12: C0103: Constant name "x" doesn't conform to '[a-z\\_][a-z0-9\\_]{2,30}$' pattern (invalid-name)
------------------------------------------------------------------
Your code has been rated at 8.95/10 (previous run: 5.26/10, +3.68)You can read up_ on regular expressions or use a website to help you_.
.. tip::
It would really be a pain to specify that regex on the command line all the time, particularly if we're using many other options.
That's what a configuration file is for. We can configure our Pylint to
store our options for us so we don't have to declare them on the command line. Using a configuration file is a nice way of formalizing your rules and
quickly sharing them with others. Invoking pylint --generate-toml-config will create a sample .toml section with all the options set and explained in comments.
This can then be added to your pyproject.toml file or any other .toml file pointed to with the --rcfile option.
.. _read up: https://docs.python.org/library/re.html
.. _a website to help you: https://regex101.com/
Doc Whatsnew Full Changelog Explanation (`doc/whatsnew/full_changelog_explanation.rst`)
From pylint's beginning to pylint 2.14.0 included, we had a changelog that contained all
nontrivial changes to Pylint, including changes that were
not user facing, i.e. change that might interest you only if you're a developer
working on pylint or pylint plugins or an open-source historian.
Doc Whatsnew Index (`doc/whatsnew/index.rst`)
.. _whatsnew-index:
.. toctree::
:maxdepth: 2
:titlesonly:
:hidden:
4/index
3/index
2/index
1/index
0/index
Doc Whatsnew Summary Explanation (`doc/whatsnew/summary_explanation.rst`)
From pylint 1.6.0 to 2.14.0, on top of the full changelog there was also a summary
of (mostly user facing) changes.
Doc Additional Tools Pyreverse Configuration (`doc/additional_tools/pyreverse/configuration.rst`)
.. This file is auto-generated. Make any changes to the associated
.. docs extension in 'doc/exts/pyreverse_configuration.py'.
Usage
pyreverse is run from the command line using the following syntax::
pyreverse [options]
where ```` is one or more Python packages or modules to analyze.
The available options are organized into the following categories:
- :ref:
filtering-and-scope- Control which classes and relationships appear in your diagrams - :ref:
display-options- Customize the visual appearance including colors and labels - :ref:
output-control- Select output formats and set the destination directory - :ref:
project-configuration- Define project settings like source roots and ignored files
.. _filtering-and-scope:
Filtering and Scope
--all-ancestors
Show all ancestors of all classes in .
Default: None
--all-associated
Show all classes associated with the target classes, including indirect associations.
Default: None
--class
Create a class diagram with all classes related to
Default: None
--filter-mode
Filter attributes and functions according to
'PUB_ONLY' filter all non public attributes [DEFAULT], equivalent to PRIVATE+SPECIAL
'ALL' no filter
'SPECIAL' filter Python special functions except constructor
'OTHER' filter protected and private attributes
Default: PUB_ONLY
--max-depth
Maximum depth of packages/modules to include in the diagram, relative to the deepest specified package. A depth of 0 shows only the specified packages/modules, while 1 includes their immediate children, etc. When specifying nested packages, depth is calculated from the deepest package level. If not specified, all packages/modules in the hierarchy are shown.
Default: None
--show-ancestors
Show
Default: None
--show-associated
Show
Default: None
--show-builtin
Include builtin objects in representation of classes.
Default: False
--show-stdlib
Include standard library objects in representation of classes.
Default: False
.. _display-options:
Display Options
--color-palette
Comma separated list of colors to use for the package depth coloring.
Default: ('#77AADD', '#99DDFF', '#44BB99', '#BBCC33', '#AAAA00', '#EEDD88', '#EE8866', '#FFAABB', '#DDDDDD')
--colorized
Use colored output. Classes/modules of the same package get the same color.
Default: False
--max-color-depth
Use separate colors up to package depth of
Default: 2
--module-names
Include module name in the representation of classes.
Default: None
--no-signatures
Show method names without parameter lists or return type annotations.
Default: False
--no-standalone
Only show nodes with connections.
Default: False
--only-classnames
Don't show attributes and methods in the class boxes; this disables -f values.
Default: False
.. _output-control:
Output Control
--output
*Create a .Graphviz output formats <https://graphviz.org/docs/outputs/>_).
Default: dot
--output-directory
Set the output directory path.
Default: ""
.. _project-configuration:
Project Configuration
--ignore
Files or directories to be skipped. They should be base names, not paths.
Default: ('CVS',)
--project
Set the project name. This will later be appended to the output file names.
Default: ""
--source-roots
Add paths to the list of the source roots. Supports globbing patterns. The source root is an absolute path or a path relative to the current working directory used to determine a package namespace for modules located under the source root.
Default: ()
--verbose
Makes pyreverse more verbose/talkative. Mostly useful for debugging.
Default: False
Doc Additional Tools Pyreverse Index (`doc/additional_tools/pyreverse/index.rst`)
.. _pyreverse:
========= Pyreverse
pyreverse is a powerful tool that creates UML diagrams from your Python code. It helps you visualize:
- Package dependencies and structure
- Class hierarchies and relationships
- Method and attribute organization
For a detailed external guide explaining the meaning of each arrow and relationship, please see this UML Class Diagram Arrows Guide <https://paulrumyancev.medium.com/uml-class-diagram-arrows-guide-37e4b1bb11e>_.
Output Formats
pyreverse supports multiple output formats:
Native formats:
.dot/.gv(Graphviz).puml/.plantuml(PlantUML).mmd/.html(MermaidJS)
Additional formats (requires Graphviz installation):
- All
Graphviz output formats <https://graphviz.org/docs/outputs/>_ (PNG, SVG, PDF, etc.) pyreversefirst generates a temporary.gvfile, which is then fed to Graphviz to generate the final image
- All
Getting Started
Check out the :doc:configuration guide to learn about available options, or see :doc:output_examples
for sample diagrams and common use cases.
.. toctree::
:maxdepth: 2
:caption: Pyreverse
:titlesonly:
:hidden:
configuration
output_examples
Doc Additional Tools Pyreverse Output Examples (`doc/additional_tools/pyreverse/output_examples.rst`)
Example Output
##############
Example diagrams generated with the .puml output format are shown below.
Package Diagram
...............
.. image:: ../../media/pyreverse_example_packages.png
:width: 344
:height: 177
:alt: Package diagram generated by pyreverse
:align: center
Class Diagram
.............
.. image:: ../../media/pyreverse_example_classes.png
:width: 625
:height: 589
:alt: Class diagram generated by pyreverse
:align: center
Creating Class Diagrams for Specific Classes
''''''''''''''''''''''''''''''''''''''''''''
In many cases creating a single diagram depicting all classes in the project yields a rather unwieldy, giant diagram.
While limiting the input path to a single package or module can already help greatly to narrow down the scope, the -c option
provides another way to create a class diagram focusing on a single class and its collaborators.
For example, running::
pyreverse -ASmy -c pylint.checkers.classes.ClassChecker pylint
will generate the full class and package diagrams for pylint, but will additionally generate a file pylint.checkers.classes.ClassChecker.dot:
.. image:: ../../media/ClassChecker_diagram.png
:width: 757
:height: 1452
:alt: Package diagram generated by pyreverse
:align: center
Doc Additional Tools Symilar Index (`doc/additional_tools/symilar/index.rst`)
.. _symilar:
Symilar
The console script symilar finds copy pasted block of text in a set of files. It provides a command line interface to check only the duplicate-code message.
It can be invoked with::
symilar [-d|--duplicates min_duplicated_lines] [-i|--ignore-comments] [--ignore-docstrings] [--ignore-imports] [--ignore-signatures] file1...
All files that shall be checked have to be passed in explicitly, e.g.::
symilar foo.py, bar.py, subpackage/spam.py, subpackage/eggs.py
symilar produces output like the following::
17 similar lines in 2 files
==tests/data/clientmodule_test.py:3
==tests/data/suppliermodule_test.py:12
class Ancestor:
""" Ancestor method """
cls_member = DoNothing()
def __init__(self, value):
local_variable = 0
self.attr = 'this method shouldn\'t have a docstring'
self.__value = value
def get_value(self):
""" nice docstring ;-) """
return self.__value
def set_value(self, value):
self.__value = value
return 'this method shouldn\'t have a docstring'TOTAL lines=58 duplicates=17 percent=29.31
Doc Development Guide Api Index (`doc/development_guide/api/index.rst`)
API
You can call Pylint, symilar and pyreverse from another
Python program thanks to their APIs:
.. sourcecode:: python
from pylint import run_pylint, run_pyreverse, run_symilar
run_pylint(["--disable=C", "myfile.py"])
run_pyreverse(...)
run_symilar(...).. toctree::
:maxdepth: 1
:hidden:
pylint
Doc Development Guide Api Pylint (`doc/development_guide/api/pylint.rst`)
======= Pylint
As you would launch the command line
You can use the run_pylint function, which is the same function
called by the command line (using sys.argv). You can supply
arguments yourself:
.. sourcecode:: python
from pylint import run_pylint
run_pylint(argv=["--disable=line-too-long", "myfile.py"])Recover the result in a stream
You can also use pylint.lint.Run directly if you want to do something that
can't be done using only pylint's command line options. Here's the basic example:
.. sourcecode:: python
from pylint.lint import Run
Run(argv=["--disable=line-too-long", "myfile.py"])With Run it is possible to invoke pylint programmatically with a
reporter initialized with a custom stream:
.. sourcecode:: python
from io import StringIO
from pylint.lint import Run
from pylint.reporters.text import TextReporter
pylint_output = StringIO() # Custom open stream
reporter = TextReporter(pylint_output)
Run(["test_file.py"], reporter=reporter, exit=False)
print(pylint_output.getvalue()) # Retrieve and print the text reportThe reporter can accept any stream object as as parameter. In this example,
the stream outputs to a file:
.. sourcecode:: python
from pylint.lint import Run
from pylint.reporters.text import TextReporter
with open("report.out", "w") as f:
reporter = TextReporter(f)
Run(["test_file.py"], reporter=reporter, exit=False)This would be useful to capture pylint output in an open stream which
can be passed onto another program.
If your program expects that the files being linted might be edited
between runs, you will need to clear pylint's inference cache:
.. sourcecode:: python
from pylint.lint import pylinter
pylinter.MANAGER.clear_cache()Doc Development Guide Contributor Guide Contribute (`doc/development_guide/contributor_guide/contribute.rst`)
============== Contributing
.. _repository:
Finding something to do
Want to contribute to pylint? There's a lot of things you can do.
Here's a list of links you can check depending on what you want to do:
Asking a question on discord, oron githubOpening an issue_Making the documentation better_Making the error message better_Reproducing bugs and confirming that issues are valid_Investigating or debugging complicated issues_Designing or specifying a solution_Giving your opinion on ongoing discussion_Fixing bugs and crashes_Fixing false positives_Creating new features or fixing false negatives_Reviewing pull requests_
.. _Asking a question on discord: https://discord.com/invite/qYxpadCgkx
.. _on github: https://github.com/pylint-dev/pylint/issues/new/choose
.. _Opening an issue: https://github.com/pylint-dev/pylint/issues/new?assignees=&labels=Needs+triage+%3Ainbox_tray%3A&template=BUG-REPORT.yml
.. _Making the documentation better: https://github.com/pylint-dev/pylint/issues?q=is%3Aopen+is%3Aissue+label%3A%22Documentation+%3Agreen_book%3A%22
.. _Making the error message better: https://github.com/pylint-dev/pylint/issues?q=is%3Aopen%20is%3Aissue%20project%3Apylint-dev%2Fpylint%2F4
.. _Reproducing bugs and confirming that issues are valid: https://github.com/pylint-dev/pylint/issues?q=is%3Aopen+is%3Aissue+label%3A%22Needs+reproduction+%3Amag%3A%22%2C%22Cannot+reproduce+%F0%9F%A4%B7%22
.. _Investigating or debugging complicated issues: https://github.com/pylint-dev/pylint/issues?q=is%3Aopen+is%3Aissue+label%3A%22Needs+investigation+%F0%9F%94%AC%22
.. _Designing or specifying a solution: https://github.com/pylint-dev/pylint/issues?q=is%3Aopen+is%3Aissue+label%3A%22Needs+design+proposal+%3Alock%3A%22%2C%22Needs+specification+%3Aclosed_lock_with_key%3A%22
.. _Giving your opinion on ongoing discussion: https://github.com/pylint-dev/pylint/issues?q=is%3Aopen+is%3Aissue+label%3A%22Needs+decision+%3Alock%3A%22
.. _Fixing bugs and crashes: https://github.com/pylint-dev/pylint/issues?q=is%3Aopen+is%3Aissue+label%3A%22Bug+%3Abeetle%3A%22%2C%22Crash+%F0%9F%92%A5%22
.. _Fixing false positives: https://github.com/pylint-dev/pylint/issues?q=is%3Aopen+is%3Aissue+label%3A%22False+Positive+%F0%9F%A6%9F%22
.. _Creating new features or fixing false negatives: https://github.com/pylint-dev/pylint/issues?q=is%3Aopen+is%3Aissue+label%3A%22False+Negative+%F0%9F%A6%8B%22%2C%22Enhancement+%E2%9C%A8%22
.. _Reviewing pull requests: https://github.com/pylint-dev/pylint/pulls?q=is%3Aopen+is%3Apr+label%3A%22Needs+review+%F0%9F%94%8D%22
If you are a pylint maintainer there's also:
Triaging issues_Labeling issues that do not have an actionable label yet_Preparing the next patch release_Checking stale pull requests status_
.. _Triaging issues: https://github.com/pylint-dev/pylint/issues?q=is%3Aopen+is%3Aissue+label%3A%22Needs+triage+%3Ainbox_tray%3A%22
.. _Labeling issues that do not have an actionable label yet: https://github.com/pylint-dev/pylint/issues?q=is%3Aopen+is%3Aissue+-label%3A%22Needs+astroid+Brain+%F0%9F%A7%A0%22+-label%3A%22Needs+astroid+update%22+-label%3A%22Needs+backport%22+-label%3A%22Needs+decision+%3Alock%3A%22+-label%3A%22Needs+investigation+%F0%9F%94%AC%22+-label%3A%22Needs+PR%22+-label%3A%22Needs+reproduction+%3Amag%3A%22+-label%3A%22Needs+review+%F0%9F%94%8D%22+-label%3A%22Needs+triage+%3Ainbox_tray%3A%22+-label%3A%22Waiting+on+author%22+-label%3A%22Work+in+progress%22+-label%3AMaintenance+sort%3Aupdated-desc+-label%3A%22Needs+specification+%3Aclosed_lock_with_key%3A%22+-label%3A%22Needs+design+proposal+%3Alock%3A%22
.. _Preparing the next patch release: https://github.com/pylint-dev/pylint/issues?q=is%3Aopen+is%3Aissue+label%3A%22Needs+backport%22
.. _Checking stale pull requests status: https://github.com/pylint-dev/pylint/pulls?q=is%3Aopen+is%3Apr+label%3A%22Work+in+progress%22%2C%22Needs+astroid+update%22%2C%22Waiting+on+author%22
Creating a pull request
Got a change for Pylint? Below are a few steps you should take to make sure
your patch gets accepted:
You must use at least Python 3.8 for development of Pylint as it gives
you access to the latestastparser and some pre-commit hooks do not
support python 3.7.Install the dev dependencies, see :ref:
contributor_install.Use our test suite and write new tests, see :ref:
contributor_testing.
.. keep this in sync with the description of PULL_REQUEST_TEMPLATE.md!
Document your change, if it is a non-trivial one:
- A maintainer might label the issue
skip-newsif the change does not need to be in the changelog. - Otherwise, create a news fragment with
towncrier create .<type>which will be
included in the changelog.<type>can be one of the types defined in./towncrier.toml.
If necessary you can write details or offer examples on how the new change is supposed to work. - Generating the doc is done with
tox -e docs
- A maintainer might label the issue
Send a pull request from GitHub (see
About pull requests_ for more insight about this topic).Write comprehensive commit messages and/or a good description of what the PR does.
Relate your change to an issue in the tracker if such an issue exists (seeClosing issues via commit messages_ of the GitHub documentation for more
information on this)Keep the change small, separate the consensual changes from the opinionated one.
- Don't hesitate to open multiple PRs if the change requires it. If your review is so
big it requires to actually plan and allocate time to review, it's more likely
that it's going to go stale. - Maintainers might have multiple 5 to 10 minutes review windows per day, Say while waiting
for their teapot to boil, or for their partner to recover from their hilarious nerdy joke,
but only one full hour review time per week, if at all.
- Don't hesitate to open multiple PRs if the change requires it. If your review is so
If you used multiple emails or multiple names when contributing, add your mails
and preferred name in thescript/.contributors_aliases.jsonfile.
.. _Closing issues via commit messages: https://github.blog/2013-01-22-closing-issues-via-commit-messages/
.. _About pull requests: https://support.github.com/features/pull-requests
.. _tox: https://tox.readthedocs.io/en/latest/
.. _pytest: https://docs.pytest.org/en/latest/
.. _black: https://github.com/psf/black
.. _isort: https://github.com/PyCQA/isort
.. _astroid: https://github.com/pylint-dev/astroid
Tips for Getting Started with Pylint Development
Read the :ref:
technical-reference. It gives a short walk through of the pylint
codebase and will help you identify where you will need to make changes
for what you are trying to implement.astroid.extract_nodeis your friend. Most checkers are AST based,
so you will likely need to interact withastroid.
A short example of how to useastroid.extract_nodeis given
:ref:here <astroid_extract_node>.When fixing a bug for a specific check, search the code for the warning
message to find where the warning is raised,
and therefore where the logic for that code exists.When adding a new checker class you can use the :file:
get_unused_message_id_category.py
script in :file:./scriptto get a message id that is not used by
any of the other checkers.
Building the documentation
You can use the makefile in the doc directory to build the documentation::
$ make -C doc/ install-dependencies
$ make -C doc/ html
We're reusing generated files for speed, use make clean or tox -e docs when you want to start from scratch.
How to choose the target version ?
Choose depending on the kind of change you're doing:
.. include:: patch_release.rst
.. include:: minor_release.rst
.. include:: major_release.rst
Doc Development Guide Contributor Guide Governance (`doc/development_guide/contributor_guide/governance.rst`)
============ Governance
How to become part of the project ?
How to become a contributor ?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Follow the code of conduct
- Search by yourself before asking for help
- Open an issue
- Investigate an issue and report your finding
- Open a merge request directly if you feel it's a consensual change
Reporting a bug is being a contributor already.
How to become a triager ?
^^^^^^^^^^^^^^^^^^^^^^^^^
- Create a pylint plugin, then migrate it to the 'pylint-dev' github organization.
Or:
- Contribute for more than 3 releases consistently.
- Do not be too opinionated, follow the code of conduct without requiring emotional
works from the maintainers. It does not mean that disagreements are impossible,
only that arguments should stay technical and reasonable so the conversation
is civil and productive. - Have a maintainer suggest that you become triager, without you asking
- Get unanimous approval or neutral agreement from current maintainers.
How to become a maintainer ?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Take ownership of a part of the code that is not maintained well at the moment
or that you contributed personally (if we feel we can't merge something without
your review, you're going to be able to merge those yourself soon).
Or:
- Contribute two big code merge requests over multiple releases (for example
one checker in 2.13 and the following bug after release and one complicated
bug fixes in 2.14). Otherwise contributing for more than 3 releases consistently
with great technical and interpersonal skills. - Triage for multiple months (close duplicate, clean up issues, answer questions...)
- Have an admin suggest that you become maintainer, without you asking
- Get unanimous approval or neutral agreement from current maintainers.
How to become an admin ?
^^^^^^^^^^^^^^^^^^^^^^^^
- Contribute for several hundreds of commits over a long period of time
with excellent interpersonal skills and code quality. - Maintain pylint for multiple years (code review, triaging and maintenance tasks).
- At this point probably have another admin leave the project or
become inactive for years. - Have an admin suggest that you become an admin, without you asking.
- Get unanimous approval or neutral agreement from current admins.
How are decisions made ?
Everyone is expected to follow the code of conduct. pylint is a do-ocracy / democracy.
You're not allowed to behave poorly because you contributed a lot. But if
you're not going to do the future maintenance work, your valid opinions might not be
taken into account by those that will be affected by it.
What are the fundamental tenets of pylint development?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
General:
We favor correctness over performance, because pylint is not used primarily
for its performance. Performance is still important and needs to be taken into
account from the get go.We then favor false negatives over false positives if correctness is
impossible to achieve.We try to keep the configuration sane, but if there's a hard decision to take we
add an option so that pylint is multiple sizes fit all (after configuration)
Where to add a new checker or message:
Error messages (things that will result in an error if run) should be builtin
checks, activated by defaultMessages that are opinionated, even slightly, should be opt-in (added as :ref:
an extension)We don't shy away from opinionated checks (like the while checker), but there's such a
thing as too opinionated, if something is too opinionated it should be an external
:ref:pylint plugin.
How are disagreements handled ?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
When something is not consensual users, maintainers, and admins discuss until an
agreement is reached.
Depending on the difficulty of the discussion and the importance of a fast resolution,
a decision can be taken:
Unanimously between discussion participants, contributors and maintainers (preferably)
By asking discussion participants for their opinions with an emoji survey in the
issue and then using the majority if no maintainers feel strongly about the issue.By majority of admins if no admins feel strongly about the issue.
By asking all users for their opinions in a new issue that will be pinned for
multiple months before taking the decision if two admins feel strongly on an
opposite side of the issue. Once the result is obvious the majority decision
is not up for discussion anymore.
Doc Development Guide Contributor Guide Index (`doc/development_guide/contributor_guide/index.rst`)
.. _contribute_guide:
Contributing to pylint
The contributor guide will help you if you want to contribute to pylint itself.
.. toctree::
:maxdepth: 2
:titlesonly:
contribute
tests/index
profiling
oss_fuzz
release
governance
Doc Development Guide Contributor Guide Major Release (`doc/development_guide/contributor_guide/major_release.rst`)
- In major releases (
1.0.0) we change everything else (pylint options, json output, dev API...)
while still trying to minimize disruption.
Doc Development Guide Contributor Guide Minor Release (`doc/development_guide/contributor_guide/minor_release.rst`)
- In minor releases (
1.2.0), we add checks, remove checks, drop python interpreters
past end of life, upgrade astroid minor/major versions and fix false negatives.
Doc Development Guide Contributor Guide Oss Fuzz (`doc/development_guide/contributor_guide/oss_fuzz.rst`)
====================== OSS-Fuzz integration
Platform overview
OSS-Fuzz <https://google.github.io/oss-fuzz/>_ is Google's free fuzzing platform for open source
software. It runs astroid's fuzz targets to help detect reliability issues that could affect astroid
and Pylint.
Google provides public build logs <https://oss-fuzz-build-logs.storage.googleapis.com/index.html#astroid>_
and fuzzing stats <https://introspector.oss-fuzz.com/project-profile?project=astroid>_, but most
of the details about bug reports and fuzzed testcases require approved access.
Gaining access
^^^^^^^^^^^^^^
The configuration files for the OSS-Fuzz integration can be found in theOSS-Fuzz repository <https://github.com/google/oss-fuzz/tree/master/projects/astroid>_.
The project.yaml file controls who has access to bug reports and testcases. Ping the
maintainers if you'd like to be added to the list (note: a Google account is required for
access).
Fuzzing progress
Once you have access to OSS-Fuzz, you can log in to https://oss-fuzz.com/ with your Google account
to see a dashboard of astroid's fuzzing progress.
Testcases
^^^^^^^^^
The dashboard contains a link to a testcases page <https://oss-fuzz.com/testcases?project=astroid&open=yes>_
that lists all testcases that currently trigger a bug in astroid.
Every testcase has a dedicated page with links to view and download a minimized testcase for
reproducing the failure. Each testcase page also contains a stacktrace for the failure and stats
about how often the failure is encountered while fuzzing.
Reproducing a failure
"""""""""""""""""""""
You can download a minimized testcase and run it locally to debug a failure on your machine.
For example, to reproduce a failure with the fuzz_parse fuzz target, you can run the following
commands:
.. code:: bash
mkdir fuzzing-repro
cd fuzzing-repro
uv venv --python 3.14
source .venv/bin/activate
git clone https://github.com/pylint-dev/astroid.git
cd astroid
uv pip install atheris==3.1.0
uv pip install --editable .
Save the minimized testcase as `minimized.py` in the astroid directory
cat << EOF > ./run_fuzz_parse.py
import astroid
import atheris
with open('minimized.py', 'rb') as f:
fdp = atheris.FuzzedDataProvider(f.read())
code = fdp.ConsumeUnicodeNoSurrogates(fdp.ConsumeIntInRange(0, 4096))
astroid.builder.parse(code)
EOF
python ./run_fuzz_parse.py
If the failure does not reproduce locally, you can try reproducing the issue in an OSS-Fuzz
container:
.. code:: bash
git clone https://github.com/google/oss-fuzz.git
cd oss-fuzz
python infra/helper.py build_image astroid
python infra/helper.py build_fuzzers astroid
python infra/helper.py reproduce astroid fuzz_parse minimized.py
Some failures may only be reproducible in an OSS-Fuzz container because of differences in Python
versions between the OSS-Fuzz platform and your local environment.
Code coverage
^^^^^^^^^^^^^
The dashboard also links to code coverage data for individual fuzz targets and combined code
coverage data for all targets (click on the "TOTAL COVERAGE" link for the combined data).
The combined coverage data is helpful for identifying coverage gaps, insufficient corpus data, and
potential candidates for future fuzz targets.
Bug reports
^^^^^^^^^^^
Bug reports for new failures are automatically filed in the OSS-Fuzz bug tracker with anastroid label <https://issues.oss-fuzz.com/issues?q=project:astroid%20status:open>_.
Make sure you are logged in to view all existing issues.
Build maintenance
Google runs compiled fuzz targets on Google Compute Engine VMs. This architecture requires each
project to provide a Dockerfile and build.sh script to download code, configure
dependencies, compile fuzz targets, and package any corpus files.
astroid's build files and fuzz-target code can be found in theOSS-Fuzz repo <https://github.com/google/oss-fuzz/blob/master/projects/astroid/>_.
If dependencies change or if new fuzz targets are added, then you may need to modify the build files
and build a new Docker image for OSS-Fuzz.
Building an image
^^^^^^^^^^^^^^^^^
Run the following commands to build astroid's OSS-Fuzz image and fuzz targets:
.. code:: bash
git clone https://github.com/google/oss-fuzz.git
cd oss-fuzz
python infra/helper.py build_image astroid
python infra/helper.py build_fuzzers astroid
Any changes you make to the build files must be submitted as pull requests to the OSS-Fuzz repo.
Debugging build failures
""""""""""""""""""""""""
You can debug build failures during the build_fuzzers stage by creating a container and manually
running the compile command:
.. code:: bash
Create a container for building fuzz targets
python infra/helper.py shell astroid
Run this command inside the container to build the fuzz targets
compile
The build.sh script will be located at /src/build.sh inside the container.
Quick links
OSS-Fuzz dashboard <https://oss-fuzz.com/>_OSS-Fuzz configuration files, build scripts, and fuzz targets for astroid <https://github.com/google/oss-fuzz/tree/master/projects/astroid>_All open OSS-Fuzz bugs for astroid <https://issues.oss-fuzz.com/issues?q=project:astroid%20status:open>_Google's OSS-Fuzz documentation <https://google.github.io/oss-fuzz/>_
Doc Development Guide Contributor Guide Patch Release (`doc/development_guide/contributor_guide/patch_release.rst`)
- In patch release (
1.2.3), we only fix false positives and crashes.
Doc Development Guide Contributor Guide Profiling (`doc/development_guide/contributor_guide/profiling.rst`)
.. -- coding: utf-8 --
.. _profiling:
=================================== Profiling and performance analysis
Performance analysis for Pylint
To analyse the performance of Pylint we recommend to use the cProfile module
from stdlib. Together with the pstats module this should give you all the tools
you need to profile a Pylint run and see which functions take how long to run.
The documentation for both modules can be found at cProfile_.
To profile a run of Pylint over itself you can use the following code and run it from the base directory.
Note that cProfile will create a document called stats that is then read by pstats. The
human-readable output will be stored by pstats in ./profiler_stats. It will be sorted bycumulative time:
.. sourcecode:: python
import cProfile
import pstats
import sys
sys.argv = ["pylint", "pylint"]
cProfile.run("from pylint import __main__", "stats")
with open("profiler_stats", "w", encoding="utf-8") as file:
stats = pstats.Stats("stats", stream=file)
stats.sort_stats("cumtime")
stats.print_stats()You can also interact with the stats object by sorting or restricting the output.
For example, to only print functions from the pylint module and sort by cumulative time you could
use:
.. sourcecode:: python
import cProfile
import pstats
import sys
sys.argv = ["pylint", "pylint"]
cProfile.run("from pylint import __main__", "stats")
with open("profiler_stats", "w", encoding="utf-8") as file:
stats = pstats.Stats("stats", stream=file)
stats.sort_stats("cumtime")
stats.print_stats("pylint/pylint")Lastly, to profile a run over your own module or code you can use:
.. sourcecode:: python
import cProfile
import pstats
import sys
sys.argv = ["pylint", "your_dir/your_file"]
cProfile.run("from pylint import __main__", "stats")
with open("profiler_stats", "w", encoding="utf-8") as file:
stats = pstats.Stats("stats", stream=file)
stats.sort_stats("cumtime")
stats.print_stats()The documentation of the pstats module discusses other possibilities to interact with
the profiling output.
Performance analysis of a specific checker
To analyse the performance of specific checker within Pylint we can use the human-readable output
created by pstats.
If you search in the profiler_stats file for the file name of the checker you will find all functional
calls from functions within the checker. Let's say we want to check the visit_importfrom method of thevariables checker::
ncalls tottime percall cumtime percall filename:lineno(function)
622 0.006 0.000 8.039 0.013 /MY_PROGRAMMING_DIR/pylint/pylint/checkers/variables.py:1445(visit_importfrom)The previous line tells us that this method was called 622 times during the profile and we were inside the
function itself for 6 ms in total. The time per call is less than a millisecond (0.006 / 622)
and thus is displayed as being 0.
Often you are more interested in the cumulative time (per call). This refers to the time spent within the function
and any of the functions it called or the functions they called (etc.). In our example, the visit_importfrom
method and all of its child-functions took a little over 8 seconds to execute, with an execution time of
0.013 ms per call.
You can also search the profiler_stats for an individual function you want to check. For example_analyse_fallback_blocks, a function called by visit_importfrom in the variables checker. This
allows more detailed analysis of specific functions::
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 /MY_PROGRAMMING_DIR/pylint/pylint/checkers/variables.py:1511(_analyse_fallback_blocks)Parsing the profiler stats with other tools
Often you might want to create a visual representation of your profiling stats. A good tool
to do this is gprof2dot_. This tool can create a .dot file from the profiling stats
created by cProfile and pstats. You can then convert the .dot file to a .png
file with one of the many converters found online.
You can read the gprof2dot_ documentation for installation instructions for your specific environment.
Another option would be snakeviz_.
.. _cProfile: https://docs.python.org/3/library/profile.html
.. _gprof2dot: https://github.com/jrfonseca/gprof2dot
.. _snakeviz: https://jiffyclub.github.io/snakeviz/
Doc Development Guide Contributor Guide Release (`doc/development_guide/contributor_guide/release.rst`)
Releasing a pylint version
So, you want to release the X.Y.Z version of pylint ?
Releasing a major or minor version
Before releasing a major or minor version check if there are any
unreleased commits on the maintenance branch. If so, release a last
patch release first. See Releasing a patch version.
- Write the
Summary -- Release highlightsindoc/whatsnewand
upgrade the release date. - Install the release dependencies:
pip3 install -r requirements_test.txt. This pins the exactastroidversion used by the CI (seerequirements_test_min.txt).
Make sure this pinned version is the one installed before runningtbump: a differentastroidproduces different functional test
output, which then gets committed into the release and breaks the CI. - Bump the version and release by using
tbump X.Y.0 --no-push --no-tag. (For example:tbump 2.4.0 --no-push --no-tag) - Check the commit created with
git showamend the commit if
required. - Move the
mainbranch up to a dev version withtbump:
.. code:: bash
tbump X.Y+1.0-dev0 --no-tag --no-push # You can interrupt after the first step
git commit -am "Upgrade the version to x.y+1.0-dev0 following x.y.0 release"
For example:
.. code:: bash
tbump 2.5.0-dev0 --no-tag --no-push
git commit -am "Upgrade the version to 2.5.0-dev0 following 2.4.0 release"
- tbump will have created a new
What's new in Pylint X.Y+1document.
Add it todoc/whatsnew/X/index.rst. Take a look at the examples fromdoc/whatsnew.
Commit that withgit commit -a --amend. - Push to a release branch
- Open a merge request with the two commits (no one can push directly
onmain) - After the merge, recover the merged commits on
mainand tag the
first one (the version should beX.Y.Z) asvX.Y.Z(For
example:v2.4.0) - Push the tag.
- Release the version on GitHub with the same name as the tag and copy
and paste the appropriate changelog in the description. This triggers
the PyPI release. - Create a
maintenance/X.Y.x(For example:maintenance/2.4.x
from thev2.4.0tag.) - Upgrade the pattern for the protected branches in the settings under
Branches/Branch protection rules. (For example:maintenance/2.4*instead ofmaintenance/2.3*.). Thereโs a lot
of configuration done in these settings, do NOT recreate it from
scratch. - Delete the
maintenance/X.Y-1.xbranch. (For example:maintenance/2.3.x) - Select all the closed issues labelled
backport maintenance/X.Y-1.xand
label thembackported, then rename thebackport maintenance/X.Y-1.xlabel tobackport maintenance/X.Y.x(for example renamebackport maintenance/2.3.xtobackport maintenance/2.4.x) - Close the current milestone and create the new ones (For example:
close2.4.0, create2.4.1and2.6.0) - Hide and deactivate all the patch releases for the previous minor
release onreadthedocs <https://readthedocs.org/projects/pylint/versions/>__,
except the last one. (For example: hidev2.4.0,v2.4.1,v2.4.2and keep onlyv2.4.3)
Back-porting a fix from ``main`` to the maintenance branch
Whenever a PR on main should be released in a patch release on the
current maintenance branch:
Label the PR with
backport maintenance/X.Y-1.x. (For examplebackport maintenance/2.3.x)Squash the PR before merging (alternatively rebase if thereโs a
single commit)(If the automated cherry-pick has conflicts)
Add a
Needs backportlabel and do it manually.You might alternatively also:
- Cherry-pick the changes that create the conflict if itโs not a
new feature before doing the original PR cherry-pick manually. - Decide to wait for the next minor to release the PR
- In any case upgrade the milestones in the original PR and newly
cherry-picked PR to match reality.
- Cherry-pick the changes that create the conflict if itโs not a
Release a patch version
Releasing a patch version
We release patch versions when a crash or a bug is fixed on the main
branch and has been cherry-picked on the maintenance branch.
- Install the release dependencies:
pip3 install -r requirements_test.txt. This pins the exactastroidversion used by the CI (seerequirements_test_min.txt).
Make sure this pinned version is the one installed before runningtbump: a differentastroidproduces different functional test
output, which then gets committed into the release and breaks the CI. - Bump the version and release by using
tbump X.Y-1.Z --no-push.
(For example:tbump 2.3.5 --no-push) - Check the result visually with
git show. - Open a merge request of
release-X.Y-1.Z'inmaintenance/X.Y.x
(For example:release-2.3.5-branchinmaintenance/2.3.x) to
run the CI tests for this branch. - Create and push the tag.
- Release the version on GitHub with the same name as the tag and copy
and paste the changelog from the ReadtheDoc generated documentation
from the pull request pipeline in the description. This triggers the
PyPI release. - Merge the
maintenance/X.Y.xbranch on the main branch. The main
branch should have the changelog forX.Y-1.Z+1(For examplev2.3.6). This merge is required sopre-commit autoupdate
works for pylint. - Fix version conflicts properly, or bump the version to
X.Y.0-devZ
(For example:2.4.0-dev6) before pushing on the main branch - Close the current milestone and create the new one (For example:
close2.3.5, create2.3.6)
Milestone handling
We move issues that were not done to the next milestone and block
releases only if there are any open issues labelled as blocker.
Doc Development Guide How Tos Custom Checkers (`doc/development_guide/how_tos/custom_checkers.rst`)
.. _write_a_checker:
How to Write a Checker
You can find some simple examples in the distribution
(custom.py <https://github.com/pylint-dev/pylint/blob/main/examples/custom.py>_
,custom_raw.py <https://github.com/pylint-dev/pylint/blob/main/examples/custom_raw.py>_
anddeprecation_checker.py <https://github.com/pylint-dev/pylint/blob/main/examples/deprecation_checker.py>_).
.. TODO Create custom_token.py
There are three kinds of checkers:
- Raw checkers, which analyse each module as a raw file stream.
- Token checkers, which analyse a file using the list of tokens that
represent the source code in the file. - AST checkers, which work on an AST representation of the module.
The AST representation is provided by the astroid library.astroid adds additional information and methods
over ast in the standard library,
to make tree navigation and code introspection easier.
.. TODO Writing a Raw Checker
.. TODO Writing a Token Checker
Writing an AST Checker
Let's implement a checker to make sure that all return nodes in a function
return a unique constant.
Firstly we will need to fill in some required boilerplate:
.. code-block:: python
import astroid
from astroid import nodes
from typing import TYPE_CHECKING, Optional
from pylint.checkers import BaseChecker
if TYPE_CHECKING:
from pylint.lint import PyLinter
class UniqueReturnChecker(BaseChecker):
name = "unique-returns"
msgs = {
"W0001": (
"Returns a non-unique constant.",
"non-unique-returns",
"All constants returned in a function should be unique.",
),
}
options = (
(
"ignore-ints",
{
"default": False,
"type": "yn",
"metavar": "<y or n>",
"help": "Allow returning non-unique integers",
},
),
)So far we have defined the following required components of our checker:
A name. The name is used to generate a special configuration
section for the checker, when options have been provided.A message dictionary. Each checker is being used for finding problems
in your code, the problems being displayed to the user through messages.
The message dictionary should specify what messages the checker is
going to emit. SeeDefining a Message_ for the details about defining a new message.
We have also defined an optional component of the checker.
The options list defines any user configurable options.
It has the following format::
options = (
("option-symbol", {"argparse-like-kwarg": "value"}),
)The
option-symbolis a unique name for the option.
This is used on the command line and in config files.
The hyphen is replaced by an underscore when used in the checker,
similarly to how you would useargparse.Namespace:.. code-block:: python
if not self.linter.config.ignore_ints:
...
Next we'll track when we enter and leave a function.
.. code-block:: python
def init(self, linter: Optional["PyLinter"] = None) -> None:
super().init(linter)
self._function_stack = []
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._function_stack.append([])
def leave_functiondef(self, node: nodes.FunctionDef) -> None:
self._function_stack.pop()
In the constructor we initialise a stack to keep a list of return nodes
for each function.
An AST checker is a visitor, and should implementvisit_<lowered class name> or leave_<lowered class name>
methods for the nodes it's interested in.
In this case we have implemented visit_functiondef and leave_functiondef
to add a new list of return nodes for this function,
and to remove the list of return nodes when we leave the function.
Finally we'll implement the check.
We will define a visit_return function,
which is called with an .astroid.nodes.Return node.
.. _astroid_extract_node:
.. TODO We can shorten/remove this bit once astroid has API docs.
We'll need to be able to figure out what attributes an.astroid.nodes.Return node has available.
We can use astroid.extract_node for this::
node = astroid.extract_node("return 5")
node
<Return l.1 at 0x7efe62196390>
help(node)
node.value
<Const.int l.1 at 0x7efe62196ef0>
We could also construct a more complete example::
node_a, node_b = astroid.extract_node("""
... def test():
... if True:
... return 5 #@
... return 5 #@
... """)
node_a.value
<Const.int l.4 at 0x7efe621a74e0>
node_a.value.value
5
node_a.value.value == node_b.value.value
True
For astroid.extract_node, you can use #@ at the end of a line to choose which statements will be extracted into nodes.
For more information on astroid.extract_node,
see the astroid documentation <https://pylint.readthedocs.io/projects/astroid/en/latest/>_.
Now we know how to use the astroid node, we can implement our check.
.. code-block:: python
def visit_return(self, node: nodes.Return) -> None:
if not isinstance(node.value, nodes.Const):
return
for other_return in self._function_stack[-1]:
if node.value.value == other_return.value.value and not (
self.linter.config.ignore_ints and node.value.pytype() == int
):
self.add_message("non-unique-returns", node=node)
self._function_stack[-1].append(node)Once we have established that the source code has failed our check,
we use ~.BaseChecker.add_message to emit our failure message.
Finally, we need to register the checker with pylint.
Add the register function to the top level of the file.
.. code-block:: python
def register(linter: "PyLinter") -> None:
"""This required method auto registers the checker during initialization.
:param linter: The linter to register the checker to.
"""
linter.register_checker(UniqueReturnChecker(linter))
We are now ready to debug and test our checker!
Debugging a Checker
It is very simple to get to a point where we can use pdb.
We'll need a small test case.
Put the following into a Python file:
.. code-block:: python
def test():
if True:
return 5
return 5
def test2():
if True:
return 1
return 5
After inserting pdb into our checker and installing it,
we can run pylint with only our checker::
$ pylint --load-plugins=my_plugin --disable=all --enable=non-unique-returns test.py
(Pdb)
Now we can debug our checker!
.. Note::
``my_plugin`` refers to a module called ``my_plugin.py``.
The preferred way of making this plugin available to pylint is
by installing it as a package. This can be done either from a packaging index like
``PyPI`` or by installing it from a local source such as with ``pip install``.
Alternatively, the plugin module can be made available to pylint by
putting this module's parent directory in your ``PYTHONPATH``
environment variable.
If your pylint config has an ``init-hook`` that modifies
``sys.path`` to include the module's parent directory, this
will also work, but only if either:
* the ``init-hook`` and the ``load-plugins`` list are both
defined in a configuration file, or...
* the ``init-hook`` is passed as a command-line argument and
the ``load-plugins`` list is in the configuration file
So, you cannot load a custom plugin by modifying ``sys.path`` if you
supply the ``init-hook`` in a configuration file, but pass the module name
in via ``--load-plugins`` on the command line.
This is because pylint loads plugins specified on command
line before loading any configuration from other sources.Defining a Message
Pylint message is defined using the following format::
msgs = {
"E0401": ( # message id
"Unable to import %s", # template of displayed message
"import-error", # message symbol
"Used when pylint has been unable to import a module.", # Message description
{ # Additional parameters:
# message control support for the old names of the messages:
"old_names": [("F0401", "old-import-error")]
"minversion": (3, 5), # No check under this version
"maxversion": (3, 7), # No check above this version
},
),
The message is then formatted using the args parameter from add_message i.e. inself.add_message("import-error", args=module_we_cant_import, node=importnode), the value in module_we_cant_import say patglib will be interpolled and the final result will be:Unable to import patglib
The
message-idshould be a 4-digit number,
prefixed with a message category.
There are multiple message categories,
these beingC,W,E,F,R,
standing forConvention,Warning,Error,FatalandRefactoring.
The 4 digits should not conflict with existing checkers
and the first 2 digits should consistent across the checker (except shared messages).
It is safe to use 51-99 as the first 2 digits for custom checkers because this range is reserved for them.The
displayed-messageis used for displaying the message to the user,
once it is emitted.The
message-symbolis an alias of the message id
and it can be used wherever the message id can be used.The
message-helpis used when callingpylint --help-msg.
Optionally message can contain optional extra options:
The
old_namesoption permits to change the message id or symbol of a message without breaking the message control used on the old messages by users. The option is specified as a list
of tuples (message-id,old-message-symbol) e.g.{"old_names": [("F0401", "old-import-error")]}.
The symbol / msgid association must be unique so if you're changing the message id the symbol also need to change and you can generally use theold-prefix for that.The
minversionormaxversionoptions specify minimum or maximum version of python
relevant for this message. The option value is specified as tuple with major version number
as first number and minor version number as second number e.g.{"minversion": (3, 5)}The
sharedoption enables sharing message between multiple checkers. As mentioned
previously, normally the message cannot be shared between multiple checkers.
To allow having message shared between multiple checkers, thesharedoption must
be set toTrue.
Parallelize a Checker
BaseChecker has two methods get_map_data and reduce_map_data that
permit to parallelize the checks when used with the -j option. If a checker
actually needs to reduce data it should define get_map_data as returning
something different than None and let its reduce_map_data handle a list
of the types returned by get_map_data.
An example can be seen by looking at pylint/checkers/similar.py.
Testing a Checker
Pylint is very well suited to test driven development.
You can implement the template of the checker,
produce all of your test cases and check that they fail,
implement the checker,
then check that all of your test cases work.
Pylint provides a pylint.testutils.CheckerTestCase
to make test cases very simple.
We can use the example code that we used for debugging as our test cases.
.. code-block:: python
import astroid
import my_plugin
import pylint.testutils
class TestUniqueReturnChecker(pylint.testutils.CheckerTestCase):
CHECKER_CLASS = my_plugin.UniqueReturnChecker
def test_finds_non_unique_ints(self):
func_node, return_node_a, return_node_b = astroid.extract_node("""
def test(): #@
if True:
return 5 #@
return 5 #@
""")
self.checker.visit_functiondef(func_node)
self.checker.visit_return(return_node_a)
with self.assertAddsMessages(
pylint.testutils.MessageTest(
msg_id="non-unique-returns",
node=return_node_b,
),
):
self.checker.visit_return(return_node_b)
def test_ignores_unique_ints(self):
func_node, return_node_a, return_node_b = astroid.extract_node("""
def test(): #@
if True:
return 1 #@
return 5 #@
""")
with self.assertNoMessages():
self.checker.visit_functiondef(func_node)
self.checker.visit_return(return_node_a)
self.checker.visit_return(return_node_b)Once again we are using astroid.extract_node to
construct our test cases.pylint.testutils.CheckerTestCase has created the linter and checker for us,
we simply simulate a traversal of the AST tree
using the nodes that we are interested in.
Doc Development Guide How Tos Index (`doc/development_guide/how_tos/index.rst`)
How To Guides
.. toctree::
:maxdepth: 2
:titlesonly:
custom_checkers
plugins
transform_plugins
Doc Development Guide How Tos Plugins (`doc/development_guide/how_tos/plugins.rst`)
.. -- coding: utf-8 --
.. _plugins:
How To Write a Pylint Plugin
Pylint provides support for writing two types of extensions.
First, there is the concept of checkers,
which can be used for finding problems in your code.
Secondly, there is also the concept of transform plugin,
which represents a way through which the inference and
the capabilities of Pylint can be enhanced
and tailored to a particular module, library of framework.
In general, a plugin is a module which should have a function register,
which takes an instance of pylint.lint.PyLinter as input.
A plugin can optionally define a function, load_configuration,
which takes an instance of pylint.lint.PyLinter as input. This
function is called after Pylint loads configuration from configuration
file and command line interface. This function should load additional
plugin specific configuration to Pylint.
So a basic hello-world plugin can be implemented as:
.. sourcecode:: python
Inside hello_plugin.py
from typing import TYPE_CHECKING
import astroid
if TYPE_CHECKING:
from pylint.lint import PyLinter
def register(linter: "PyLinter") -> None:
"""This required method auto registers the checker during initialization.
:param linter: The linter to register the checker to.
"""
print('Hello world')We can run this plugin by placing this module in the PYTHONPATH and invoking
pylint as:
.. sourcecode:: bash
$ pylint -E --load-plugins hello_plugin foo.py
Hello world
We can extend hello-world plugin to ignore some specific names usingload_configuration function:
.. sourcecode:: python
Inside hello_plugin.py
from typing import TYPE_CHECKING
import astroid
if TYPE_CHECKING:
from pylint.lint import PyLinter
def register(linter: "PyLinter") -> None:
"""This required method auto registers the checker during initialization.
:param linter: The linter to register the checker to.
"""
print('Hello world')def load_configuration(linter):
name_checker = get_checker(linter, NameChecker)
# We consider as good names of variables Hello and World
name_checker.config.good_names += ('Hello', 'World')
# We ignore bin directory
linter.config.black_list += ('bin',)Depending if we need a transform plugin or a checker, this might not
be enough. For the former, this is enough to declare the module as a plugin,
but in the case of the latter, we need to register our checker with the linter
object, by calling the following inside the register function::
linter.register_checker(OurChecker(linter))For more information on writing a checker see :ref:write_a_checker.
Doc Development Guide How Tos Transform Plugins (`doc/development_guide/how_tos/transform_plugins.rst`)
Transform plugins
^^^^^^^^^^^^^^^^^
Why write a plugin?
Pylint is a static analysis tool and Python is a dynamically typed language.
So there will be cases where Pylint cannot analyze files properly (this problem
can happen in statically typed languages also if reflection or dynamic
evaluation is used).
The plugins are a way to tell Pylint how to handle such cases,
since only the user would know what needs to be done. They are usually operating
on the AST level, by modifying or changing it in a way which can ease its
understanding by Pylint.
Example
Let us run Pylint on a module from the Python source: warnings.py_ and see what happens:
.. sourcecode:: shell
amitdev$ pylint -E Lib/warnings.py
E:297,36: Instance of 'WarningMessage' has no 'message' member (no-member)
E:298,36: Instance of 'WarningMessage' has no 'filename' member (no-member)
E:298,51: Instance of 'WarningMessage' has no 'lineno' member (no-member)
E:298,64: Instance of 'WarningMessage' has no 'line' member (no-member)
Did we catch a genuine error? Let's open the code and look at WarningMessage class:
.. sourcecode:: python
class WarningMessage(object):
"""Holds the result of a single showwarning() call."""
_WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
"line")
def __init__(self, message, category, filename, lineno, file=None,
line=None):
local_values = locals()
for attr in self._WARNING_DETAILS:
setattr(self, attr, local_values[attr])
self._category_name = category.__name__ if category else None
def __str__(self):
...Ah, the fields (message, category etc) are not defined statically on the class.
Instead they are added using setattr. Pylint would have a tough time figuring
this out.
Enter Plugin
We can write a transform plugin to tell Pylint how to analyze this properly.
One way to fix our example with a plugin would be to transform the WarningMessage class,
by setting the attributes so that Pylint can see them. This can be done by
registering a transform function. We can transform any node in the parsed AST like
Module, Class, Function etc. In our case we need to transform a class. It can be done so:
.. sourcecode:: python
from typing import TYPE_CHECKING
import astroid
if TYPE_CHECKING:
from pylint.lint import PyLinter
def register(linter: "PyLinter") -> None:
"""This required method auto registers the checker during initialization.
:param linter: The linter to register the checker to.
"""
pass def transform(cls):
if cls.name == 'WarningMessage':
import warnings
for f in warnings.WarningMessage._WARNING_DETAILS:
cls.locals[f] = [astroid.ClassDef(f, None)]
astroid.MANAGER.register_transform(astroid.ClassDef, transform)
Let's go through the plugin. First, we need to register a class transform, which
is done via the register_transform function in MANAGER. It takes the node
type and function as parameters. We need to change a class, so we use astroid.ClassDef.
We also pass a transform function which does the actual transformation.
transform function is simple as well. If the class is WarningMessage then we
add the attributes to its locals (we are not bothered about type of attributes, so setting
them as class will do. But we could set them to any type we want). That's it.
Note: We don't need to do anything in the register function of the plugin since we
are not modifying anything in the linter itself.
Lets run Pylint with this plugin and see:
.. sourcecode:: bash
amitdev$ pylint -E --load-plugins warning_plugin Lib/warnings.py
amitdev$
All the false positives associated with WarningMessage are now gone. This is just
an example, any code transformation can be done by plugins.
See astroid/brain_ for real life examples of transform plugins.
.. _warnings.py: https://hg.python.org/cpython/file/2.7/Lib/warnings.py
.. _astroid/brain: https://github.com/pylint-dev/astroid/tree/main/astroid/brain
Doc Development Guide Technical Reference Checkers (`doc/development_guide/technical_reference/checkers.rst`)
Checkers
All of the default pylint checkers exist in pylint.checkers.
This is where most of pylint's brains exist.
Most checkers are AST based and so use astroid.pylint.checkers.utils provides a large number of utility methods for
dealing with astroid.
Doc Development Guide Technical Reference Index (`doc/development_guide/technical_reference/index.rst`)
.. _technical-reference:
Technical Reference
.. TODO Configuration
.. TODO Messages
.. TODO Reports
.. extensions.rst and features.rst are generated.
.. toctree::
:maxdepth: 2
:titlesonly:
startup
checkers
Doc Development Guide Technical Reference Startup (`doc/development_guide/technical_reference/startup.rst`)
Startup and the Linter Class
The two main classes in pylint.lint are.pylint.lint.Run and .pylint.lint.PyLinter.
The .pylint.lint.Run object is responsible for starting up pylint.
It does some basic checking of the given command line options to
find the initial hook to run,
find the config file to use,
and find which plugins have been specified.
It can then create the main .pylint.lint.PyLinter instance
and initialise it with the config file and plugins that were discovered
when preprocessing the command line options.
Finally the .pylint.lint.Run object launches any child linters
for parallel jobs, and starts the linting process.
The .pylint.lint.PyLinter is responsible for coordinating the
linting process.
It parses the configuration and provides it for the checkers and other plugins,
it handles the messages emitted by the checkers,
it handles the output reporting,
and it launches the checkers.
Doc User Guide Checkers Extensions (`doc/user_guide/checkers/extensions.rst`)
Optional checkers
.. This file is auto-generated. Make any changes to the associated
.. docs extension in 'doc/exts/pylint_extensions.py'.
Pylint provides the following optional plugins:
- :ref:
pylint.extensions.bad_builtin - :ref:
pylint.extensions.broad_try_clause - :ref:
pylint.extensions.check_elif - :ref:
pylint.extensions.code_style - :ref:
pylint.extensions.comparison_placement - :ref:
pylint.extensions.confusing_elif - :ref:
pylint.extensions.consider_refactoring_into_while_condition - :ref:
pylint.extensions.consider_ternary_expression - :ref:
pylint.extensions.dict_init_mutate - :ref:
pylint.extensions.docparams - :ref:
pylint.extensions.docstyle - :ref:
pylint.extensions.dunder - :ref:
pylint.extensions.empty_comment - :ref:
pylint.extensions.eq_without_hash - :ref:
pylint.extensions.for_any_all - :ref:
pylint.extensions.magic_value - :ref:
pylint.extensions.mccabe - :ref:
pylint.extensions.no_self_use - :ref:
pylint.extensions.overlapping_exceptions - :ref:
pylint.extensions.private_import - :ref:
pylint.extensions.redefined_loop_name - :ref:
pylint.extensions.redefined_variable_type - :ref:
pylint.extensions.set_membership - :ref:
pylint.extensions.typing - :ref:
pylint.extensions.while_used
You can activate any or all of these extensions by adding a load-plugins line to the MAIN section of your .pylintrc, for example::
load-plugins=pylint.extensions.docparams,pylint.extensions.docstyle.. _pylint.extensions.broad_try_clause:
Broad Try Clause checker
This checker is provided by ``pylint.extensions.broad_try_clause``.
Verbatim name of the checker is ``broad_try_clause``.
See also :ref:`broad_try_clause checker's options' documentation `
Broad Try Clause checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:too-many-try-statements (W0717):
Try clause contains too many statements.
.. _pylint.extensions.code_style:
Code Style checker
~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.code_style``.
Verbatim name of the checker is ``code_style``.
Code Style checker Documentation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Checkers that can improve code consistency.
As such they don't necessarily provide a performance benefit and
are often times opinionated.
See also :ref:`code_style checker's options' documentation <code_style-options>`
Code Style checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^
:consider-using-namedtuple-or-dataclass (R6101): *Consider using namedtuple or dataclass for dictionary values*
Emitted when dictionary values can be replaced by namedtuples or dataclass
instances.
:consider-using-tuple (R6102): *Consider using an in-place tuple instead of list*
Only for style consistency! Emitted where an in-place defined ``list`` can be
replaced by a ``tuple``. Due to optimizations by CPython, there is no
performance benefit from it.
:consider-using-assignment-expr (R6103): *Use '%s' instead*
Emitted when an if assignment is directly followed by an if statement and
both can be combined by using an assignment expression ``:=``. Requires
Python 3.8 and ``py-version >= 3.8``.
:consider-using-augmented-assign (R6104): *Use '%s' to do an augmented assign directly*
Emitted when an assignment is referring to the object that it is assigning
to. This can be changed to be an augmented assign. Disabled by default!
:prefer-typing-namedtuple (R6105): *Prefer 'typing.NamedTuple' over 'collections.namedtuple'*
'typing.NamedTuple' uses the well-known 'class' keyword with type-hints for
readability (it's also faster as it avoids an internal exec call). Disabled
by default!
:consider-math-not-float (R6106): *Consider %smath.%s instead of %s*
Using math.inf or math.nan permits to benefit from typing and it is up to 4
times faster than a float call (after the initial import of math). This check
also catches typos in float calls as a side effect.
.. _pylint.extensions.comparison_placement:
Comparison-Placement checkerThis checker is provided by pylint.extensions.comparison_placement.
Verbatim name of the checker is comparison-placement.
Comparison-Placement checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:misplaced-comparison-constant (C2201): Comparison should be %s
Used when the constant is placed on the left side of a comparison. It is
usually clearer in intent to place it in the right hand side of the
comparison.
.. _pylint.extensions.confusing_elif:
Confusing Elif checker
This checker is provided by ``pylint.extensions.confusing_elif``.
Verbatim name of the checker is ``confusing_elif``.
Confusing Elif checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:confusing-consecutive-elif (R5601): *Consecutive elif with differing indentation level, consider creating a function to separate the inner elif*
Used when an elif statement follows right after an indented block which
itself ends with if or elif. It may not be obvious if the elif statement was
willingly or mistakenly unindented. Extracting the indented if statement into
a separate function might avoid confusion and prevent errors.
.. _pylint.extensions.for_any_all:
Consider-Using-Any-Or-All checkerThis checker is provided by pylint.extensions.for_any_all.
Verbatim name of the checker is consider-using-any-or-all.
Consider-Using-Any-Or-All checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:consider-using-any-or-all (C0501): for loop could be %s
A for loop that checks for a condition and return a bool can be replaced with
any or all.
.. _pylint.extensions.consider_refactoring_into_while_condition:
Consider Refactoring Into While checker
This checker is provided by ``pylint.extensions.consider_refactoring_into_while_condition``.
Verbatim name of the checker is ``consider_refactoring_into_while``.
Consider Refactoring Into While checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:consider-refactoring-into-while-condition (R3501): *Consider using 'while %s' instead of 'while %s:' an 'if', and a 'break'*
Emitted when `while True:` loop is used and the first statement is a break
condition. The ``if / break`` construct can be removed if the check is
inverted and moved to the ``while`` statement.
.. _pylint.extensions.consider_ternary_expression:
Consider Ternary Expression checker
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.consider_ternary_expression``.
Verbatim name of the checker is ``consider_ternary_expression``.
Consider Ternary Expression checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:consider-ternary-expression (W0160): *Consider rewriting as a ternary expression*
Multiple assign statements spread across if/else blocks can be rewritten with
a single assignment and ternary expression
.. _pylint.extensions.bad_builtin:
Deprecated Builtins checker
~~~~~~~~~~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.bad_builtin``.
Verbatim name of the checker is ``deprecated_builtins``.
Deprecated Builtins checker Documentation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This used to be the ``bad-builtin`` core checker, but it was moved to
an extension instead. It can be used for finding prohibited used builtins,
such as ``map`` or ``filter``, for which other alternatives exists.
If you want to control for what builtins the checker should warn about,
you can use the ``bad-functions`` option::
$ pylint a.py --load-plugins=pylint.extensions.bad_builtin --bad-functions=apply,reduce
...
See also :ref:`deprecated_builtins checker's options' documentation <deprecated_builtins-options>`
Deprecated Builtins checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:bad-builtin (W0141): *Used builtin function %s*
Used when a disallowed builtin function is used (see the bad-function
option). Usual disallowed functions are the ones like map, or filter , where
Python offers now some cleaner alternative like list comprehension.
.. _pylint.extensions.mccabe:
Design checker
~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.mccabe``.
Verbatim name of the checker is ``design``.
Design checker Documentation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You can now use this plugin for finding complexity issues in your code base.
Activate it through ``pylint --load-plugins=pylint.extensions.mccabe``. It introduces
a new warning, ``too-complex``, which is emitted when a code block has a complexity
higher than a preestablished value, which can be controlled through the
``max-complexity`` option.
.. note::
Both this extension and Pylint's built-in design checker are named ``design``.
The built-in checker is enabled by default and reports messages such as
``too-many-arguments`` and ``too-many-branches``, even when this extension is
not loaded. The ``too-complex`` message and ``max-complexity`` option are only
available after loading ``pylint.extensions.mccabe``.
To disable individual design checks while keeping ``too-complex``, disable
their message names. ``--disable=design`` disables both checkers' messages.
For example::
$ cat a.py
def f10():
"""McCabe rating: 11"""
myint = 2
if myint == 5:
return myint
elif myint == 6:
return myint
elif myint == 7:
return myint
elif myint == 8:
return myint
elif myint == 9:
return myint
elif myint == 10:
if myint == 8:
while True:
return True
elif myint == 8:
with myint:
return 8
else:
if myint == 2:
return myint
return myint
return myint
$ pylint a.py --load-plugins=pylint.extensions.mccabe
R:1: 'f10' is too complex. The McCabe rating is 11 (too-complex)
$ pylint a.py --load-plugins=pylint.extensions.mccabe --max-complexity=50
$
See also :ref:`design checker's options' documentation <design-options>`
Design checker Messages
^^^^^^^^^^^^^^^^^^^^^^^
:too-complex (R1260): *%s is too complex. The McCabe rating is %d*
Used when a method or function is too complex based on McCabe Complexity
Cyclomatic
.. _pylint.extensions.dict_init_mutate:
Dict-Init-Mutate checker
~~~~~~~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.dict_init_mutate``.
Verbatim name of the checker is ``dict-init-mutate``.
Dict-Init-Mutate checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:dict-init-mutate (C3401): *Declare all known key/values when initializing the dictionary: %s*
Dictionaries can be initialized with a single statement using dictionary
literal syntax.
.. _pylint.extensions.docstyle:
Docstyle checker
~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.docstyle``.
Verbatim name of the checker is ``docstyle``.
Docstyle checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^
:bad-docstring-quotes (C0198): *Bad docstring quotes in %s, expected """, given %s*
Used when a docstring does not have triple double quotes.
:docstring-first-line-empty (C0199): *First line empty in %s docstring*
Used when a blank line is found at the beginning of a docstring.
.. _pylint.extensions.dunder:
Dunder checker
~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.dunder``.
Verbatim name of the checker is ``dunder``.
See also :ref:`dunder checker's options' documentation <dunder-options>`
Dunder checker Messages
^^^^^^^^^^^^^^^^^^^^^^^
:bad-dunder-name (W3201): *Bad or misspelled dunder method name %s.*
Used when a dunder method is misspelled or defined with a name not within the
predefined list of dunder names.
.. _pylint.extensions.check_elif:
Else If Used checker
~~~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.check_elif``.
Verbatim name of the checker is ``else_if_used``.
Else If Used checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:else-if-used (R5501): *Consider using "elif" instead of "else" then "if" to remove one indentation level*
Used when an else statement is immediately followed by an if statement and
does not contain statements that would be unrelated to it.
.. _pylint.extensions.empty_comment:
Empty-Comment checker
~~~~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.empty_comment``.
Verbatim name of the checker is ``empty-comment``.
Empty-Comment checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:empty-comment (R2044): *Line with empty comment*
Used when a # symbol appears on a line not followed by an actual comment
.. _pylint.extensions.eq_without_hash:
Eq-Without-Hash checker
~~~~~~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.eq_without_hash``.
Verbatim name of the checker is ``eq-without-hash``.
Eq-Without-Hash checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:eq-without-hash (W1641): *Implementing __eq__ without also implementing __hash__*
Used when a class implements __eq__ but not __hash__. Objects get None as
their default __hash__ implementation if they also implement __eq__.
.. _pylint.extensions.private_import:
Import-Private-Name checker
~~~~~~~~~~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.private_import``.
Verbatim name of the checker is ``import-private-name``.
Import-Private-Name checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:import-private-name (C2701): *Imported private %s (%s)*
Used when a private module or object prefixed with _ is imported. PEP8
guidance on Naming Conventions states that public attributes with leading
underscores should be considered private.
.. _pylint.extensions.magic_value:
Magic-Value checker
~~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.magic_value``.
Verbatim name of the checker is ``magic-value``.
See also :ref:`magic-value checker's options' documentation <magic-value-options>`
Magic-Value checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:magic-value-comparison (R2004): *Consider using a named constant or an enum instead of '%s'.*
Using named constants instead of magic values helps improve readability and
maintainability of your code, try to avoid them in comparisons.
.. _pylint.extensions.redefined_variable_type:
Multiple Types checker
~~~~~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.redefined_variable_type``.
Verbatim name of the checker is ``multiple_types``.
Multiple Types checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:redefined-variable-type (R0204): *Redefinition of %s type from %s to %s*
Used when the type of a variable changes inside a method or a function.
.. _pylint.extensions.no_self_use:
No Self Use checker
~~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.no_self_use``.
Verbatim name of the checker is ``no_self_use``.
No Self Use checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:no-self-use (R6301): *Method could be a function*
Used when a method doesn't use its bound instance, and so could be written as
a function.
.. _pylint.extensions.overlapping_exceptions:
Overlap-Except checker
~~~~~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.overlapping_exceptions``.
Verbatim name of the checker is ``overlap-except``.
Overlap-Except checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:overlapping-except (W0714): *Overlapping exceptions (%s)*
Used when exceptions in handler overlap or are identical
.. _pylint.extensions.docparams:
Parameter Documentation checker
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.docparams``.
Verbatim name of the checker is ``parameter_documentation``.
Parameter Documentation checker Documentation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If you document the parameters of your functions, methods and constructors and
their types systematically in your code this optional component might
be useful for you. Sphinx style, Google style, and Numpy style are supported.
(For some examples, see https://pypi.org/project/sphinxcontrib-napoleon/ .)
You can activate this checker by adding the line::
load-plugins=pylint.extensions.docparams
to the ``MAIN`` section of your ``.pylintrc``.
This checker verifies that all function, method, and constructor docstrings
include documentation of the
* parameters and their types
* return value and its type
* exceptions raised
and can handle docstrings in
* Sphinx style (``param``, ``type``, ``return``, ``rtype``,
``raise`` / ``except``)::
def function_foo(x, y, z):
'''function foo ...
:param x: bla x
:type x: int
:param y: bla y
:type y: float
:param int z: bla z
:return: sum
:rtype: float
:raises OSError: bla
'''
return x + y + z
* or the Google style (``Args:``, ``Returns:``, ``Raises:``)::
def function_foo(x, y, z):
'''function foo ...
Args:
x (int): bla x
y (float): bla y
z (int): bla z
Returns:
float: sum
Raises:
OSError: bla
'''
return x + y + z
* or the Numpy style (``Parameters``, ``Returns``, ``Raises``)::
def function_foo(x, y, z):
'''function foo ...
Parameters
----------
x: int
bla x
y: float
bla y
z: int
bla z
Returns
-------
float
sum
Raises
------
OSError
bla
'''
return x + y + z
You'll be notified of **missing parameter documentation** but also of
**naming inconsistencies** between the signature and the documentation which
often arise when parameters are renamed automatically in the code, but not in
the documentation.
**Note:** by default docstrings of private and magic methods are not checked.
To change this behaviour (for example, to also check ``__init__``) add
``no-docstring-rgx=^(?!__init__$)_`` to the ``BASIC`` section of your ``.pylintrc``.
Constructor parameters can be documented in either the class docstring or
the ``__init__`` docstring, but not both::
class ClassFoo(object):
'''Sphinx style docstring foo
:param float x: bla x
:param y: bla y
:type y: int
'''
def __init__(self, x, y):
pass
class ClassBar(object):
def __init__(self, x, y):
'''Google style docstring bar
Args:
x (float): bla x
y (int): bla y
'''
pass
In some cases, having to document all parameters is a nuisance, for instance if
many of your functions or methods just follow a **common interface**. To remove
this burden, the checker accepts missing parameter documentation if one of the
following phrases is found in the docstring:
* For the other parameters, see
* For the parameters, see
(with arbitrary whitespace between the words). Please add a link to the
docstring defining the interface, e.g. a superclass method, after "see"::
def callback(x, y, z):
'''Sphinx style docstring for callback ...
:param x: bla x
:type x: int
For the other parameters, see
:class:`MyFrameworkUsingAndDefiningCallback`
'''
return x + y + z
def callback(x, y, z):
'''Google style docstring for callback ...
Args:
x (int): bla x
For the other parameters, see
:class:`MyFrameworkUsingAndDefiningCallback`
'''
return x + y + z
Naming inconsistencies in existing parameter and their type documentations are
still detected.
See also :ref:`parameter_documentation checker's options' documentation `
Parameter Documentation checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:multiple-constructor-doc (W9005): *"%s" has constructor parameters documented in class and %s*
Please remove parameter declarations in the class or constructor.
:missing-raises-doc (W9006): *"%s" not documented as being raised*
Please document exceptions for all raised exception types.
:redundant-returns-doc (W9008): *Redundant returns documentation*
Please remove the return/rtype documentation from this method.
:redundant-yields-doc (W9010): *Redundant yields documentation*
Please remove the yields documentation from this method.
:missing-return-doc (W9011): *Missing return documentation*
Please add documentation about what this method returns.
:missing-return-type-doc (W9012): *Missing return type documentation*
Please document the type returned by this method.
:missing-yield-doc (W9013): *Missing yield documentation*
Please add documentation about what this generator yields.
:missing-yield-type-doc (W9014): *Missing yield type documentation*
Please document the type yielded by this method.
:missing-param-doc (W9015): *"%s" missing in parameter documentation*
Please add parameter declarations for all parameters.
:missing-type-doc (W9016): *"%s" missing in parameter type documentation*
Please add parameter type declarations for all parameters.
:differing-param-doc (W9017): *"%s" differing in parameter documentation*
Please check parameter names in declarations.
:differing-type-doc (W9018): *"%s" differing in parameter type documentation*
Please check parameter names in type declarations.
:useless-param-doc (W9019): *"%s" useless ignored parameter documentation*
Please remove the ignored parameter documentation.
:useless-type-doc (W9020): *"%s" useless ignored parameter type documentation*
Please remove the ignored parameter type documentation.
:missing-any-param-doc (W9021): *Missing any documentation in "%s"*
Please add parameter and/or type documentation.
.. _pylint.extensions.redefined_loop_name:
Redefined-Loop-Name checker
~~~~~~~~~~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.redefined_loop_name``.
Verbatim name of the checker is ``redefined-loop-name``.
Redefined-Loop-Name checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:redefined-loop-name (W2901): *Redefining %r from loop (line %s)*
Used when a loop variable is overwritten in the loop body.
.. _pylint.extensions.set_membership:
Set Membership checker
~~~~~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.set_membership``.
Verbatim name of the checker is ``set_membership``.
Set Membership checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:use-set-for-membership (R6201): *Consider using set for membership test*
Membership tests are more efficient when performed on a lookup optimized
datatype like ``sets``.
.. _pylint.extensions.typing:
Typing checker
~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.typing``.
Verbatim name of the checker is ``typing``.
Typing checker Documentation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Find issue specifically related to type annotations.
See also :ref:`typing checker's options' documentation <typing-options>`
Typing checker Messages
^^^^^^^^^^^^^^^^^^^^^^^
:broken-noreturn (E6004): *'NoReturn' inside compound types is broken in 3.7.0 / 3.7.1*
``typing.NoReturn`` inside compound types is broken in Python 3.7.0 and
3.7.1. If not dependent on runtime introspection, use string annotation
instead. E.g. ``Callable[..., 'NoReturn']``.
https://bugs.python.org/issue34921
:broken-collections-callable (E6005): *'collections.abc.Callable' inside Optional and Union is broken in 3.9.0 / 3.9.1 (use 'typing.Callable' instead)*
``collections.abc.Callable`` inside Optional and Union is broken in Python
3.9.0 and 3.9.1. Use ``typing.Callable`` for these cases instead.
https://bugs.python.org/issue42965
:deprecated-typing-alias (W6001): *'%s' is deprecated, use '%s' instead*
Emitted when a deprecated typing alias is used.
:consider-using-alias (R6002): *'%s' will be deprecated with PY39, consider using '%s' instead%s*
Only emitted if 'runtime-typing=no' and a deprecated typing alias is used in
a type annotation context in Python 3.7 or 3.8.
:consider-alternative-union-syntax (R6003): *Consider using alternative union syntax instead of '%s'%s*
Emitted when ``typing.Union`` or ``typing.Optional`` is used instead of the
shorthand union syntax. For example, ``Union[int, float]`` instead of ``int |
float``. Using the shorthand for unions aligns with Python typing
recommendations, removes the need for imports, and avoids confusion in
function signatures.
:redundant-typehint-argument (R6006): *Type `%s` is used more than once in union type annotation. Remove redundant typehints.*
Duplicated type arguments will be skipped by `mypy` tool, therefore should be
removed to avoid confusion.
:unnecessary-default-type-args (R6007): *Type `%s` has unnecessary default type args. Change it to `%s`.*
Emitted when types have default type args which can be omitted. Mainly used
for `typing.Generator` and `typing.AsyncGenerator`.
.. _pylint.extensions.while_used:
While Used checker
~~~~~~~~~~~~~~~~~~
This checker is provided by ``pylint.extensions.while_used``.
Verbatim name of the checker is ``while_used``.
While Used checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^
:while-used (W0149): *Used `while` loop*
Unbounded `while` loops can often be rewritten as bounded `for` loops.
Exceptions can be made for cases such as event loops, listeners, etc.
---
### Doc User Guide Checkers Features (`doc/user_guide/checkers/features.rst`)
Pylint features
===============
.. This file is auto-generated. Make any changes to the associated
.. docs extension in 'doc/exts/pylint_features.py'.
Pylint checkers' options and switches
-------------------------------------
Pylint checkers can provide three set of features:
* options that control their execution,
* messages that they can raise,
* reports that they can generate.
Below is a list of all checkers and their features.
.. _async-checker:
Async checker
~~~~~~~~~~~~~
Verbatim name of the checker is ``async``.
Async checker Messages
^^^^^^^^^^^^^^^^^^^^^^
:yield-inside-async-function (E1700): *Yield inside async function*
Used when an `yield` or `yield from` statement is found inside an async
function. This message can't be emitted when using Python < 3.5.
:not-async-context-manager (E1701): *Async context manager '%s' doesn't implement __aenter__ and __aexit__.*
Used when an async context manager is used with an object that does not
implement the async context management protocol. This message can't be
emitted when using Python < 3.5.
.. _bad-chained-comparison-checker:
Bad-Chained-Comparison checker
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``bad-chained-comparison``.
Bad-Chained-Comparison checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:bad-chained-comparison (W3601): *Suspicious %s-part chained comparison using semantically incompatible operators (%s)*
Used when there is a chained comparison where one expression is part of two
comparisons that belong to different semantic groups ("<" does not mean the
same thing as "is", chaining them in "0 < x is None" is probably a mistake).
.. _basic-checker:
Basic checker
~~~~~~~~~~~~~
Verbatim name of the checker is ``basic``.
See also :ref:`basic checker's options' documentation `
Basic checker Messages
^^^^^^^^^^^^^^^^^^^^^^
:init-is-generator (E0100): *__init__ method is a generator*
Used when the special class method __init__ is turned into a generator by a
yield in its body.
:return-in-init (E0101): *Explicit return in __init__*
Used when the special class method __init__ has an explicit return value.
:function-redefined (E0102): *%s already defined line %s*
Used when a function / class / method is redefined.
:not-in-loop (E0103): *%r not properly in loop*
Used when break or continue keywords are used outside a loop.
:return-outside-function (E0104): *Return outside function*
Used when a "return" statement is found outside a function or method.
:yield-outside-function (E0105): *Yield outside function*
Used when a "yield" statement is found outside a function or method.
:return-arg-in-generator (E0106): *Return with argument inside generator*
Used when a "return" statement with an argument is found in a generator
function or method (e.g. with some "yield" statements). This message can't be
emitted when using Python >= 3.3.
:nonexistent-operator (E0107): *Use of the non-existent %s operator*
Used when you attempt to use the C-style pre-increment or pre-decrement
operator -- and ++, which doesn't exist in Python.
:duplicate-argument-name (E0108): *Duplicate argument name %r in function definition*
Duplicate argument names in function definitions are syntax errors.
:abstract-class-instantiated (E0110): *Abstract class %r with abstract methods instantiated*
Used when an abstract class with `abc.ABCMeta` as metaclass has abstract
methods and is instantiated.
:bad-reversed-sequence (E0111): *The first reversed() argument is not a sequence*
Used when the first argument to reversed() builtin isn't a sequence (does not
implement __reversed__, nor __getitem__ and __len__
:too-many-star-expressions (E0112): *More than one starred expression in assignment*
Emitted when there are more than one starred expressions (`*x`) in an
assignment. This is a SyntaxError.
:invalid-star-assignment-target (E0113): *Starred assignment target must be in a list or tuple*
Emitted when a star expression is used as a starred assignment target.
:star-needs-assignment-target (E0114): *Can use starred expression only in assignment target*
Emitted when a star expression is not used in an assignment target.
:nonlocal-and-global (E0115): *Name %r is nonlocal and global*
Emitted when a name is both nonlocal and global.
:nonlocal-without-binding (E0117): *nonlocal name %s found without binding*
Emitted when a nonlocal variable does not have an attached name somewhere in
the parent scopes
:used-prior-global-declaration (E0118): *Name %r is used prior to global declaration*
Emitted when a name is used prior a global declaration, which results in an
error since Python 3.6. This message can't be emitted when using Python <
3.6.
:misplaced-format-function (E0119): *format function is not called on str*
Emitted when format function is not called on str object. e.g doing
print("value: {}").format(123) instead of print("value: {}".format(123)).
This might not be what the user intended to do.
:unreachable (W0101): *Unreachable code*
Used when there is some code behind a "return" or "raise" statement, which
will never be accessed.
:dangerous-default-value (W0102): *Dangerous default value %s as argument*
Used when a mutable value as list or dictionary is detected in a default
value for an argument.
:pointless-statement (W0104): *Statement seems to have no effect*
Used when a statement doesn't have (or at least seems to) any effect.
:pointless-string-statement (W0105): *String statement has no effect*
Used when a string is used as a statement (which of course has no effect).
This is a particular case of W0104 with its own message so you can easily
disable it if you're using those strings as documentation, instead of
comments.
:expression-not-assigned (W0106): *Expression "%s" is assigned to nothing*
Used when an expression that is not a function call is assigned to nothing.
Probably something else was intended.
:unnecessary-pass (W0107): *Unnecessary pass statement*
Used when a "pass" statement can be removed without affecting the behaviour
of the code.
:unnecessary-lambda (W0108): *Lambda may not be necessary*
Used when the body of a lambda expression is a function call on the same
argument list as the lambda itself; such lambda expressions are in all but a
few cases replaceable with the function being called in the body of the
lambda.
:duplicate-key (W0109): *Duplicate key %r in dictionary*
Used when a dictionary expression binds the same key multiple times.
:useless-else-on-loop (W0120): *Else clause on loop without a break statement, remove the else and de-indent all the code inside it*
Loops should only have an else clause if they can exit early with a break
statement, otherwise the statements under else should be on the same scope as
the loop itself.
:exec-used (W0122): *Use of exec*
Raised when the 'exec' statement is used. It's dangerous to use this function
for a user input, and it's also slower than actual code in general. This
doesn't mean you should never use it, but you should consider alternatives
first and restrict the functions available.
:eval-used (W0123): *Use of eval*
Used when you use the "eval" function, to discourage its usage. Consider
using `ast.literal_eval` for safely evaluating strings containing Python
expressions from untrusted sources.
:confusing-with-statement (W0124): *Following "as" with another context manager looks like a tuple.*
Emitted when a `with` statement component returns multiple values and uses
name binding with `as` only for a part of those values, as in with ctx() as
a, b. This can be misleading, since it's not clear if the context manager
returns a tuple or if the node without a name binding is another context
manager.
:using-constant-test (W0125): *Using a conditional statement with a constant value*
Emitted when a conditional statement (If or ternary if) uses a constant value
for its test. This might not be what the user intended to do.
:missing-parentheses-for-call-in-test (W0126): *Using a conditional statement with potentially wrong function or method call due to missing parentheses*
Emitted when a conditional statement (If or ternary if) seems to wrongly call
a function due to missing parentheses
:self-assigning-variable (W0127): *Assigning the same variable %r to itself*
Emitted when we detect that a variable is assigned to itself
:redeclared-assigned-name (W0128): *Redeclared variable %r in assignment*
Emitted when we detect that a variable was redeclared in the same assignment.
:assert-on-string-literal (W0129): *Assert statement has a string literal as its first argument. The assert will %s fail.*
Used when an assert statement has a string literal as its first argument,
which will cause the assert to always pass.
:duplicate-value (W0130): *Duplicate value %r in set*
This message is emitted when a set contains the same value two or more times.
:named-expr-without-context (W0131): *Named expression used without context*
Emitted if named expression is used to do a regular assignment outside a
context like if, for, while, or a comprehension.
:pointless-exception-statement (W0133): *Exception statement has no effect*
Used when an exception is created without being assigned, raised or returned
for subsequent use elsewhere.
:return-in-finally (W0134): *'return' shadowed by the 'finally' clause.*
Emitted when a 'return' statement is found in a 'finally' block. This will
overwrite the return value of a function and should be avoided.
:contextmanager-generator-missing-cleanup (W0135): *The context used in function %r will not be exited.*
Used when a contextmanager is used inside a generator function and the
cleanup is not handled.
:continue-in-finally (W0136): *'continue' discouraged inside 'finally' clause*
Emitted when the `continue` keyword is found inside a finally clause. This
will raise a SyntaxWarning starting in Python 3.14.
:break-in-finally (W0137): *'break' discouraged inside 'finally' clause*
Emitted when the `break` keyword is found inside a finally clause. This will
raise a SyntaxWarning starting in Python 3.14.
:comparison-with-callable (W0143): *Comparing against a callable, did you omit the parenthesis?*
This message is emitted when pylint detects that a comparison with a callable
was made, which might suggest that some parenthesis were omitted, resulting
in potential unwanted behaviour.
:lost-exception (W0150): *%s statement in finally block may swallow exception*
Used when a break or a return statement is found inside the finally clause of
a try...finally block: the exceptions raised in the try clause will be
silently swallowed instead of being re-raised.
:nan-comparison (W0177): *Comparison %s should be %s*
Used when an expression is compared to NaN values like math.nan, numpy.nan or
float('nan').
:assert-on-tuple (W0199): *Assert called on a populated tuple. Did you mean 'assert x,y'?*
A call of assert on a tuple will always evaluate to true if the tuple is not
empty, and will always evaluate to false if it is.
:literal-comparison (R0123): *In '%s', use '%s' when comparing constant literals not '%s' ('%s')*
Used when comparing an object to a literal, which is usually what you do not
want to do, since you can compare to a different literal than what was
expected altogether.
:comparison-with-itself (R0124): *Redundant comparison - %s*
Used when something is compared against itself.
:comparison-of-constants (R0133): *Comparison between constants: "%s %s %s" has a constant value*
When two literals are compared with each other the result is a constant.
Using the constant directly is both easier to read and more performant.
Initializing 'True' and 'False' this way is not required since Python 2.3.
:invalid-name (C0103): *%s name "%s" doesn't conform to %s*
Used when the name doesn't conform to naming rules associated to its type
(constant, variable, class...).
:disallowed-name (C0104): *Disallowed name "%s"*
Used when the name matches bad-names or bad-names-rgxs- (unauthorized names).
:typevar-name-incorrect-variance (C0105): *Type variable name does not reflect variance%s*
Emitted when a TypeVar name doesn't reflect its type variance. According to
PEP8, it is recommended to add suffixes '_co' and '_contra' to the variables
used to declare covariant or contravariant behaviour respectively. Invariant
(default) variables do not require a suffix. The message is also emitted when
invariant variables do have a suffix.
:empty-docstring (C0112): *Empty %s docstring*
Used when a module, function, class or method has an empty docstring (it
would be too easy ;).
:missing-module-docstring (C0114): *Missing module docstring*
Used when a module has no docstring. Empty modules do not require a
docstring.
:missing-class-docstring (C0115): *Missing class docstring*
Used when a class has no docstring. Even an empty class must have a
docstring.
:missing-function-docstring (C0116): *Missing function or method docstring*
Used when a function or method has no docstring. Some special methods like
__init__ do not require a docstring.
:singleton-comparison (C0121): *Comparison %s should be %s*
Used when an expression is compared to singleton values like True, False or
None.
:unidiomatic-typecheck (C0123): *Use isinstance() rather than type() for a typecheck.*
The idiomatic way to perform an explicit typecheck in Python is to use
isinstance(x, Y) rather than type(x) == Y, type(x) is Y. Though there are
unusual situations where these give different results.
:typevar-double-variance (C0131): *TypeVar cannot be both covariant and contravariant*
Emitted when both the "covariant" and "contravariant" keyword arguments are
set to "True" in a TypeVar.
:typevar-name-mismatch (C0132): *TypeVar name "%s" does not match assigned variable name "%s"*
Emitted when a TypeVar is assigned to a variable that does not match its name
argument.
Basic checker Reports
^^^^^^^^^^^^^^^^^^^^^
:RP0101: Statistics by type
.. _classes-checker:
Classes checker
~~~~~~~~~~~~~~~
Verbatim name of the checker is ``classes``.
See also :ref:`classes checker's options' documentation <classes-options>`
Classes checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^
:method-hidden (E0202): *An attribute defined in %s line %s hides this method*
Used when a class defines a method which is hidden by an instance attribute
from an ancestor class or set by some client code.
:access-member-before-definition (E0203): *Access to member %r before its definition line %s*
Used when an instance member is accessed before it's actually assigned.
:no-method-argument (E0211): *Method %r has no argument*
Used when a method which should have the bound instance as first argument has
no argument defined.
:no-self-argument (E0213): *Method %r should have "self" as first argument*
Used when a method has an attribute different the "self" as first argument.
This is considered as an error since this is a so common convention that you
shouldn't break it!
:invalid-slots-object (E0236): *Invalid object %r in __slots__, must contain only non empty strings*
Used when an invalid (non-string) object occurs in __slots__.
:assigning-non-slot (E0237): *Assigning to attribute %r not defined in class slots*
Used when assigning to an attribute not defined in the class slots.
:invalid-slots (E0238): *Invalid __slots__ object*
Used when an invalid __slots__ is found in class. Only a string, an iterable
or a sequence is permitted.
:inherit-non-class (E0239): *Inheriting %r, which is not a class.*
Used when a class inherits from something which is not a class.
:inconsistent-mro (E0240): *Inconsistent method resolution order for class %r*
Used when a class has an inconsistent method resolution order.
:duplicate-bases (E0241): *Duplicate bases for class %r*
Duplicate use of base classes in derived classes raise TypeErrors.
:class-variable-slots-conflict (E0242): *Value %r in slots conflicts with class variable*
Used when a value in __slots__ conflicts with a class variable, property or
method.
:invalid-class-object (E0243): *Invalid assignment to '__class__'. Should be a class definition but got a '%s'*
Used when an invalid object is assigned to a __class__ property. Only a class
is permitted.
:invalid-enum-extension (E0244): *Extending inherited Enum class "%s"*
Used when a class tries to extend an inherited Enum class. Doing so will
raise a TypeError at runtime.
:declare-non-slot (E0245): *No such name %r in __slots__*
Raised when a type annotation on a class is absent from the list of names in
__slots__, and __slots__ does not contain a __dict__ entry.
:non-iterator-returned (E0301): *__iter__ returns non-iterator*
Used when an __iter__ method returns something which is not an iterable (i.e.
has no `__next__` method)
:unexpected-special-method-signature (E0302): *The special method %r expects %s param(s), %d %s given*
Emitted when a special method was defined with an invalid number of
parameters. If it has too few or too many, it might not work at all.
:invalid-length-returned (E0303): *__len__ does not return non-negative integer*
Used when a __len__ method returns something which is not a non-negative
integer
:invalid-bool-returned (E0304): *__bool__ does not return bool*
Used when a __bool__ method returns something which is not a bool
:invalid-index-returned (E0305): *__index__ does not return int*
Used when an __index__ method returns something which is not an integer
:invalid-repr-returned (E0306): *__repr__ does not return str*
Used when a __repr__ method returns something which is not a string
:invalid-str-returned (E0307): *__str__ does not return str*
Used when a __str__ method returns something which is not a string
:invalid-bytes-returned (E0308): *__bytes__ does not return bytes*
Used when a __bytes__ method returns something which is not bytes
:invalid-hash-returned (E0309): *__hash__ does not return int*
Used when a __hash__ method returns something which is not an integer
:invalid-length-hint-returned (E0310): *__length_hint__ does not return non-negative integer*
Used when a __length_hint__ method returns something which is not a non-
negative integer
:invalid-format-returned (E0311): *__format__ does not return str*
Used when a __format__ method returns something which is not a string
:invalid-getnewargs-returned (E0312): *__getnewargs__ does not return a tuple*
Used when a __getnewargs__ method returns something which is not a tuple
:invalid-getnewargs-ex-returned (E0313): *__getnewargs_ex__ does not return a tuple containing (tuple, dict)*
Used when a __getnewargs_ex__ method returns something which is not of the
form tuple(tuple, dict)
:attribute-defined-outside-init (W0201): *Attribute %r defined outside __init__*
Used when an instance attribute is defined outside the __init__ method.
:bad-staticmethod-argument (W0211): *Static method with %r as first argument*
Used when a static method has "self" or a value specified in valid-
classmethod-first-arg option or valid-metaclass-classmethod-first-arg option
as first argument.
:protected-access (W0212): *Access to a protected member %s of a client class*
Used when a protected member (i.e. class member with a name beginning with an
underscore) is accessed outside the class or a descendant of the class where
it's defined.
:implicit-flag-alias (W0213): *Flag member %(overlap)s shares bit positions with %(sources)s*
Used when multiple integer values declared within an enum.IntFlag class share
a common bit position.
:arguments-differ (W0221): *%s %s %r method*
Used when a method has a different number of arguments than in the
implemented interface or in an overridden method. Extra arguments with
default values are ignored.
:signature-differs (W0222): *Signature differs from %s %r method*
Used when a method signature is different than in the implemented interface
or in an overridden method.
:abstract-method (W0223): *Method %r is abstract in class %r but is not overridden in child class %r*
Used when an abstract method (i.e. raise NotImplementedError) is not
overridden in concrete class.
:super-init-not-called (W0231): *__init__ method from base class %r is not called*
Used when an ancestor class method has an __init__ method which is not called
by a derived class.
:non-parent-init-called (W0233): *__init__ method from a non direct base class %r is called*
Used when an __init__ method is called on a class which is not in the direct
ancestors for the analysed class.
:invalid-overridden-method (W0236): *Method %r was expected to be %r, found it instead as %r*
Used when we detect that a method was overridden in a way that does not match
its base class which could result in potential bugs at runtime.
:arguments-renamed (W0237): *%s %s %r method*
Used when a method parameter has a different name than in the implemented
interface or in an overridden method.
:unused-private-member (W0238): *Unused private member `%s.%s`*
Emitted when a private member of a class is defined but not used.
:overridden-final-method (W0239): *Method %r overrides a method decorated with typing.final which is defined in class %r*
Used when a method decorated with typing.final has been overridden.
:subclassed-final-class (W0240): *Class %r is a subclass of a class decorated with typing.final: %r*
Used when a class decorated with typing.final has been subclassed.
:redefined-slots-in-subclass (W0244): *Redefined slots %r in subclass*
Used when a slot is re-defined in a subclass.
:super-without-brackets (W0245): *Super call without brackets*
Used when a call to super does not have brackets and thus is not an actual
call and does not work as expected.
:useless-parent-delegation (W0246): *Useless parent or super() delegation in method %r*
Used whenever we can detect that an overridden method is useless, relying on
parent or super() delegation to do the same thing as another method from the
MRO.
:no-classmethod-decorator (R0202): *Consider using a decorator instead of calling classmethod*
Used when a class method is defined without using the decorator syntax.
:no-staticmethod-decorator (R0203): *Consider using a decorator instead of calling staticmethod*
Used when a static method is defined without using the decorator syntax.
:useless-object-inheritance (R0205): *Class %r inherits from object, can be safely removed from bases in python3*
Used when a class inherit from object, which under python3 is implicit, hence
can be safely removed from bases.
:property-with-parameters (R0206): *Cannot have defined parameters for properties*
Used when we detect that a property also has parameters, which are useless,
given that properties cannot be called with additional arguments.
:bad-classmethod-argument (C0202): *Class method %s should have %s as first argument*
Used when a class method has a first argument named differently than the
value specified in valid-classmethod-first-arg option (default to "cls"),
recommended to easily differentiate them from regular instance methods.
:bad-mcs-method-argument (C0203): *Metaclass method %s should have %s as first argument*
Used when a metaclass method has a first argument named differently than the
value specified in valid-classmethod-first-arg option (default to "cls"),
recommended to easily differentiate them from regular instance methods.
:bad-mcs-classmethod-argument (C0204): *Metaclass class method %s should have %s as first argument*
Used when a metaclass class method has a first argument named differently
than the value specified in valid-metaclass-classmethod-first-arg option
(default to "mcs"), recommended to easily differentiate them from regular
instance methods.
:single-string-used-for-slots (C0205): *Class __slots__ should be a non-string iterable*
Used when a class __slots__ is a simple string, rather than an iterable.
:method-check-failed (F0202): *Unable to check methods signature (%s / %s)*
Used when Pylint has been unable to check methods signature compatibility for
an unexpected reason. Please report this kind if you don't make sense of it.
.. _dataclass-checker:
Dataclass checker
~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``dataclass``.
Dataclass checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^
:invalid-field-call (E3701): *Invalid usage of field(), %s*
The dataclasses.field() specifier should only be used as the value of an
assignment within a dataclass, or within the make_dataclass() function.
.. _design-checker:
Design checker
~~~~~~~~~~~~~~
Verbatim name of the checker is ``design``.
See also :ref:`design checker's options' documentation <design-options>`
Design checker Messages
^^^^^^^^^^^^^^^^^^^^^^^
:too-many-ancestors (R0901): *Too many ancestors (%s/%s)*
Used when class has too many parent classes, try to reduce this to get a
simpler (and so easier to use) class.
:too-many-instance-attributes (R0902): *Too many instance attributes (%s/%s)*
Used when class has too many instance attributes, try to reduce this to get a
simpler (and so easier to use) class.
:too-few-public-methods (R0903): *Too few public methods (%s/%s)*
Used when class has too few public methods, so be sure it's really worth it.
:too-many-public-methods (R0904): *Too many public methods (%s/%s)*
Used when class has too many public methods, try to reduce this to get a
simpler (and so easier to use) class.
:too-many-return-statements (R0911): *Too many return statements (%s/%s)*
Used when a function or method has too many return statement, making it hard
to follow.
:too-many-branches (R0912): *Too many branches (%s/%s)*
Used when a function or method has too many branches, making it hard to
follow.
:too-many-arguments (R0913): *Too many arguments (%s/%s)*
Used when a function or method takes too many arguments.
:too-many-locals (R0914): *Too many local variables (%s/%s)*
Used when a function or method has too many local variables.
:too-many-statements (R0915): *Too many statements (%s/%s)*
Used when a function or method has too many statements. You should then split
it in smaller functions / methods.
:too-many-boolean-expressions (R0916): *Too many boolean expressions in if statement (%s/%s)*
Used when an if statement contains too many boolean expressions.
:too-many-positional-arguments (R0917): *Too many positional arguments (%s/%s)*
Used when a function has too many positional arguments.
.. _exceptions-checker:
Exceptions checker
~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``exceptions``.
See also :ref:`exceptions checker's options' documentation <exceptions-options>`
Exceptions checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^
:bad-except-order (E0701): *Bad except clauses order (%s)*
Used when except clauses are not in the correct order (from the more specific
to the more generic). If you don't fix the order, some exceptions may not be
caught by the most specific handler.
:raising-bad-type (E0702): *Raising %s while only classes or instances are allowed*
Used when something which is neither a class nor an instance is raised (i.e.
a `TypeError` will be raised).
:misplaced-bare-raise (E0704): *The raise statement is not inside an except clause*
Used when a bare raise is not used inside an except clause. This generates an
error, since there are no active exceptions to be reraised. An exception to
this rule is represented by a bare raise inside a finally clause, which might
work, as long as an exception is raised inside the try block, but it is
nevertheless a code smell that must not be relied upon.
:bad-exception-cause (E0705): *Exception cause set to something which is not an exception, nor None*
Used when using the syntax "raise ... from ...", where the exception cause is
not an exception, nor None.
:raising-non-exception (E0710): *Raising a class which doesn't inherit from BaseException*
Used when a class which doesn't inherit from BaseException is raised.
:notimplemented-raised (E0711): *NotImplemented raised - should raise NotImplementedError*
Used when NotImplemented is raised instead of NotImplementedError
:catching-non-exception (E0712): *Catching an exception which doesn't inherit from Exception: %s*
Used when a class which doesn't inherit from Exception is used as an
exception in an except clause.
:bare-except (W0702): *No exception type(s) specified*
A bare ``except:`` clause will catch ``SystemExit`` and ``KeyboardInterrupt``
exceptions, making it harder to interrupt a program with ``Control-C``, and
can disguise other problems. If you want to catch all exceptions that signal
program errors, use ``except Exception:`` (bare except is equivalent to
``except BaseException:``).
:duplicate-except (W0705): *Catching previously caught exception type %s*
Used when an except catches a type that was already caught by a previous
handler.
:try-except-raise (W0706): *The except handler raises immediately*
Used when an except handler uses raise as its first or only operator. This is
useless because it raises back the exception immediately. Remove the raise
operator or the entire try-except-raise block!
:raise-missing-from (W0707): *Consider explicitly re-raising using %s'%s from %s'*
Python's exception chaining shows the traceback of the current exception, but
also of the original exception. When you raise a new exception after another
exception was caught it's likely that the second exception is a friendly re-
wrapping of the first exception. In such cases `raise from` provides a better
link between the two tracebacks in the final error.
:binary-op-exception (W0711): *Exception to catch is the result of a binary "%s" operation*
Used when the exception to catch is of the form "except A or B:". If
intending to catch multiple, rewrite as "except (A, B):"
:raising-format-tuple (W0715): *Exception arguments suggest string formatting might be intended*
Used when passing multiple arguments to an exception constructor, the first
of them a string literal containing what appears to be placeholders intended
for formatting
:wrong-exception-operation (W0716): *Invalid exception operation. %s*
Used when an operation is done against an exception, but the operation is not
valid for the exception in question. Usually emitted when having binary
operations between exceptions in except handlers.
:broad-exception-caught (W0718): *Catching too general exception %s*
If you use a naked ``except Exception:`` clause, you might end up catching
exceptions other than the ones you expect to catch. This can hide bugs or
make it harder to debug programs when unrelated errors are hidden.
:broad-exception-raised (W0719): *Raising too general exception: %s*
Raising exceptions that are too generic force you to catch exceptions
generically too. It will force you to use a naked ``except Exception:``
clause. You might then end up catching exceptions other than the ones you
expect to catch. This can hide bugs or make it harder to debug programs when
unrelated errors are hidden.
.. _format-checker:
Format checker
~~~~~~~~~~~~~~
Verbatim name of the checker is ``format``.
See also :ref:`format checker's options' documentation <format-options>`
Format checker Messages
^^^^^^^^^^^^^^^^^^^^^^^
:unnecessary-semicolon (W0301): *Unnecessary semicolon*
Used when a statement is ended by a semi-colon (";"), which isn't necessary
(that's python, not C ;).
:bad-indentation (W0311): *Bad indentation. Found %s %s, expected %s*
Used when an unexpected number of indentation's tabulations or spaces has
been found.
:line-too-long (C0301): *Line too long (%s/%s)*
Used when a line is longer than a given number of characters.
:too-many-lines (C0302): *Too many lines in module (%s/%s)*
Used when a module has too many lines, reducing its readability.
:trailing-whitespace (C0303): *Trailing whitespace*
Used when there is whitespace between the end of a line and the newline.
:missing-final-newline (C0304): *Final newline missing*
Used when the last line in a file is missing a newline.
:trailing-newlines (C0305): *Trailing newlines*
Used when there are trailing blank lines in a file.
:multiple-statements (C0321): *More than one statement on a single line*
Used when more than one statement is found on the same line.
:superfluous-parens (C0325): *Unnecessary parens after %r keyword*
Used when a single item in parentheses follows an if, for, or other keyword.
:mixed-line-endings (C0327): *Mixed line endings LF and CRLF*
Used when there are mixed (LF and CRLF) newline signs in a file.
:unexpected-line-ending-format (C0328): *Unexpected line ending format. There is '%s' while it should be '%s'.*
Used when there is different newline than expected.
.. _imports-checker:
Imports checker
~~~~~~~~~~~~~~~
Verbatim name of the checker is ``imports``.
See also :ref:`imports checker's options' documentation <imports-options>`
Imports checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^
:import-error (E0401): *Unable to import %s*
Used when pylint has been unable to import a module.
:relative-beyond-top-level (E0402): *Attempted relative import beyond top-level package*
Used when a relative import tries to access too many levels in the current
package.
:invalid-lazy-import (E0403): *Lazy import is not allowed %s*
Emitted when a PEP 810 ``lazy`` import is used where Python forbids it:
inside a function, a class body or a ``try`` statement, or as a wildcard
import. This is a SyntaxError. This message can't be emitted when using
Python < 3.15.
:wildcard-import (W0401): *Wildcard import %s*
Used when `from module import *` is detected.
:reimported (W0404): *Reimport %r (imported line %s)*
Used when a module is imported more than once.
:import-self (W0406): *Module import itself*
Used when a module is importing itself.
:preferred-module (W0407): *Prefer importing %r instead of %r*
Used when a module imported has a preferred replacement module.
:misplaced-future (W0410): *__future__ import is not the first non docstring statement*
Python 2.5 and greater require __future__ import to be the first non
docstring statement in the module.
:shadowed-import (W0416): *Shadowed %r (imported line %s)*
Used when a module is aliased with a name that shadows another import.
:deprecated-module (W4901): *Deprecated module %r*
A module marked as deprecated is imported.
:cyclic-import (R0401): *Cyclic import (%s)*
Used when a cyclic import between two or more modules is detected.
:consider-using-from-import (R0402): *Use 'from %s import %s' instead*
Emitted when a submodule of a package is imported and aliased with the same
name, e.g., instead of ``import concurrent.futures as futures`` use ``from
concurrent import futures``.
:multiple-imports (C0410): *Multiple imports on one line (%s)*
Used when import statement importing multiple modules is detected.
:wrong-import-order (C0411): *%s should be placed before %s*
Used when PEP8 import order is not respected (standard imports first, then
third-party libraries, then local imports).
:ungrouped-imports (C0412): *Imports from package %s are not grouped*
Used when imports are not grouped by packages.
:wrong-import-position (C0413): *Import "%s" should be placed at the top of the module*
Used when code and imports are mixed.
:useless-import-alias (C0414): *Import alias does not rename original package*
Used when an import alias is same as original package, e.g., using import
numpy as numpy instead of import numpy as np.
:import-outside-toplevel (C0415): *Import outside toplevel (%s)*
Used when an import statement is used anywhere other than the module
toplevel. Move this import to the top of the file.
Imports checker Reports
^^^^^^^^^^^^^^^^^^^^^^^
:RP0401: External dependencies
:RP0402: Modules dependencies graph
.. _lambda-expressions-checker:
Lambda-Expressions checker
~~~~~~~~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``lambda-expressions``.
Lambda-Expressions checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:unnecessary-lambda-assignment (C3001): *Lambda expression assigned to a variable. Define a function using the "def" keyword instead.*
Used when a lambda expression is assigned to variable rather than defining a
standard function with the "def" keyword.
:unnecessary-direct-lambda-call (C3002): *Lambda expression called directly. Execute the expression inline instead.*
Used when a lambda expression is directly called rather than executing its
contents inline.
.. _logging-checker:
Logging checker
~~~~~~~~~~~~~~~
Verbatim name of the checker is ``logging``.
See also :ref:`logging checker's options' documentation <logging-options>`
Logging checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^
:logging-unsupported-format (E1200): *Unsupported logging format character %r (%#02x) at index %d*
Used when an unsupported format character is used in a logging statement
format string.
:logging-format-truncated (E1201): *Logging format string ends in middle of conversion specifier*
Used when a logging statement format string terminates before the end of a
conversion specifier.
:logging-too-many-args (E1205): *Too many arguments for logging format string*
Used when a logging format string is given too many arguments.
:logging-too-few-args (E1206): *Not enough arguments for logging format string*
Used when a logging format string is given too few arguments.
:logging-not-lazy (W1201): *Use %s formatting in logging functions*
Used when a logging statement has a call form of "logging.<logging
method>(format_string % (format_args...))". Use another type of string
formatting instead. You can use % formatting but leave interpolation to the
logging function by passing the parameters as arguments. If logging-fstring-
interpolation is disabled then you can use fstring formatting. If logging-
format-interpolation is disabled then you can use str.format.
:logging-format-interpolation (W1202): *Use %s formatting in logging functions*
Used when a logging statement has a call form of "logging.<logging
method>(format_string.format(format_args...))". Use another type of string
formatting instead. You can use % formatting but leave interpolation to the
logging function by passing the parameters as arguments. If logging-fstring-
interpolation is disabled then you can use fstring formatting. If logging-
not-lazy is disabled then you can use % formatting as normal.
:logging-fstring-interpolation (W1203): *Use %s formatting in logging functions*
Used when a logging statement has a call form of "logging.<logging
method>(f"...")".Use another type of string formatting instead. You can use %
formatting but leave interpolation to the logging function by passing the
parameters as arguments. If logging-format-interpolation is disabled then you
can use str.format. If logging-not-lazy is disabled then you can use %
formatting as normal.
.. _looping-through-iterator-checker:
Looping-Through-Iterator checker
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``looping-through-iterator``.
Looping-Through-Iterator checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:looping-through-iterator (W4801): *Iterator '%s' from an outer scope is reused or consumed in a nested loop.*
Used when an iterator defined in an outer loop scope is consumed in a nested
loop. Because iterators are stateful and exhausted upon consumption, the
inner loop will fully consume the iterator during the first iteration of the
outer loop, leaving it empty for all subsequent iterations.
.. _match_statements-checker:
Match Statements checker
~~~~~~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``match_statements``.
Match Statements checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:bare-name-capture-pattern (E1901): *The name capture `case %s` makes the remaining patterns unreachable. Use a dotted name (for example an enum) to fix this.*
Emitted when a name capture pattern is used in a match statement and there
are case statements below it.
:invalid-match-args-definition (E1902): *`__match_args__` must be a tuple of strings.*
Emitted if `__match_args__` isn't a tuple of strings required for match.
:too-many-positional-sub-patterns (E1903): *%s expects %d positional sub-patterns (given %d)*
Emitted when the number of allowed positional sub-patterns exceeds the number
of allowed sub-patterns specified in `__match_args__`.
:multiple-class-sub-patterns (E1904): *Multiple sub-patterns for attribute %s*
Emitted when there is more than one sub-pattern for a specific attribute in a
class pattern.
:match-class-bind-self (R1905): *Use '%s() as %s' instead*
Match class patterns are faster if the name binding happens for the whole
pattern and any lookup for `__match_args__` can be avoided.
:match-class-positional-attributes (R1906): *Use keyword attributes instead of positional ones (%s)*
Keyword attributes are more explicit and slightly faster since CPython can
skip the `__match_args__` lookup.
.. _method_args-checker:
Method Args checker
~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``method_args``.
See also :ref:`method_args checker's options' documentation <method_args-options>`
Method Args checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:positional-only-arguments-expected (E3102): *`%s()` got some positional-only arguments passed as keyword arguments: %s*
Emitted when positional-only arguments have been passed as keyword arguments.
Remove the keywords for the affected arguments in the function call.
:missing-timeout (W3101): *Missing timeout argument for method '%s' can cause your program to hang indefinitely*
Used when a method needs a 'timeout' parameter in order to avoid waiting for
a long time. If no timeout is specified explicitly the default value is used.
For example for 'requests' the program will never time out (i.e. hang
indefinitely).
.. _metrics-checker:
Metrics checker
~~~~~~~~~~~~~~~
Verbatim name of the checker is ``metrics``.
Metrics checker Reports
^^^^^^^^^^^^^^^^^^^^^^^
:RP0701: Raw metrics
.. _miscellaneous-checker:
Miscellaneous checker
~~~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``miscellaneous``.
See also :ref:`miscellaneous checker's options' documentation <miscellaneous-options>`
Miscellaneous checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:fixme (W0511):
Used when a warning note as FIXME or XXX is detected.
:use-symbolic-message-instead (I0023):
Used when a message is enabled or disabled by id.
.. _modified_iteration-checker:
Modified Iteration checker
~~~~~~~~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``modified_iteration``.
Modified Iteration checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:modified-iterating-dict (E4702): *Iterated dict '%s' is being modified inside for loop body, iterate through a copy of it instead.*
Emitted when items are added or removed to a dict being iterated through.
Doing so raises a RuntimeError.
:modified-iterating-set (E4703): *Iterated set '%s' is being modified inside for loop body, iterate through a copy of it instead.*
Emitted when items are added or removed to a set being iterated through.
Doing so raises a RuntimeError.
:modified-iterating-list (W4701): *Iterated list '%s' is being modified inside for loop body, consider iterating through a copy of it instead.*
Emitted when items are added or removed to a list being iterated through.
Doing so can result in unexpected behaviour, that is why it is preferred to
use a copy of the list.
.. _nested_min_max-checker:
Nested Min Max checker
~~~~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``nested_min_max``.
Nested Min Max checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:nested-min-max (W3301): *Do not use nested call of '%s'; it's possible to do '%s' instead*
Nested calls ``min(1, min(2, 3))`` can be rewritten as ``min(1, 2, 3)``.
.. _newstyle-checker:
Newstyle checker
~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``newstyle``.
Newstyle checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^
:bad-super-call (E1003): *Bad first argument %r given to super()*
Used when another argument than the current class is given as first argument
of the super builtin.
.. _nonascii-checker-checker:
Nonascii-Checker checker
~~~~~~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``nonascii-checker``.
Nonascii-Checker checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:non-ascii-file-name (W2402): *%s name "%s" contains a non-ASCII character.*
Under python 3.5, PEP 3131 allows non-ascii identifiers, but not non-ascii
file names.Since Python 3.5, even though Python supports UTF-8 files, some
editors or tools don't.
:non-ascii-name (C2401): *%s name "%s" contains a non-ASCII character, consider renaming it.*
Used when the name contains at least one non-ASCII unicode character. See
https://peps.python.org/pep-0672/#confusing-features for a background why
this could be bad. If your programming guideline defines that you are
programming in English, then there should be no need for non ASCII characters
in Python Names. If not you can simply disable this check.
:non-ascii-module-import (C2403): *%s name "%s" contains a non-ASCII character, use an ASCII-only alias for import.*
Used when the name contains at least one non-ASCII unicode character. See
https://peps.python.org/pep-0672/#confusing-features for a background why
this could be bad. If your programming guideline defines that you are
programming in English, then there should be no need for non ASCII characters
in Python Names. If not you can simply disable this check.
.. _refactoring-checker:
Refactoring checker
~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``refactoring``.
See also :ref:`refactoring checker's options' documentation <refactoring-options>`
Refactoring checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:consider-merging-isinstance (R1701): *Consider merging these isinstance calls to isinstance(%s, (%s))*
Used when multiple consecutive isinstance calls can be merged into one.
:too-many-nested-blocks (R1702): *Too many nested blocks (%s/%s)*
Used when a function or a method has too many nested blocks. This makes the
code less understandable and maintainable.
:simplifiable-if-statement (R1703): *The if statement can be replaced with %s*
Used when an if statement can be replaced with 'bool(test)'.
:redefined-argument-from-local (R1704): *Redefining argument with the local name %r*
Used when a local name is redefining an argument, which might suggest a
potential error. This is taken in account only for a handful of name binding
operations, such as for iteration, with statement assignment and exception
handler assignment.
:no-else-return (R1705): *Unnecessary "%s" after "return", %s*
Used in order to highlight an unnecessary block of code following an if, or a
try/except containing a return statement. As such, it will warn when it
encounters an else following a chain of ifs, all of them containing a return
statement.
:consider-using-ternary (R1706): *Consider using ternary (%s)*
Used when one of known pre-python 2.5 ternary syntax is used.
:trailing-comma-tuple (R1707): *Disallow trailing comma tuple*
In Python, a tuple is actually created by the comma symbol, not by the
parentheses. Unfortunately, one can actually create a tuple by misplacing a
trailing comma, which can lead to potential weird bugs in your code. You
should always use parentheses explicitly for creating a tuple.
:stop-iteration-return (R1708): *Do not raise StopIteration in generator, use return statement instead*
According to PEP479, the raise of StopIteration to end the loop of a
generator may lead to hard to find bugs. This PEP specify that raise
StopIteration has to be replaced by a simple return statement
:simplify-boolean-expression (R1709): *Boolean expression may be simplified to %s*
Emitted when redundant pre-python 2.5 ternary syntax is used.
:inconsistent-return-statements (R1710): *Either all return statements in a function should return an expression, or none of them should.*
According to PEP8, if any return statement returns an expression, any return
statements where no value is returned should explicitly state this as return
None, and an explicit return statement should be present at the end of the
function (if reachable)
:useless-return (R1711): *Useless return at end of function or method*
Emitted when a single "return" or "return None" statement is found at the end
of function or method definition. This statement can safely be removed
because Python will implicitly return None
:consider-swap-variables (R1712): *Consider using tuple unpacking for swapping variables*
You do not have to use a temporary variable in order to swap variables. Using
"tuple unpacking" to directly swap variables makes the intention more clear.
:consider-using-join (R1713): *Consider using str.join(sequence) for concatenating strings from an iterable*
Using str.join(sequence) is faster, uses less memory and increases
readability compared to for-loop iteration.
:consider-using-in (R1714): *Consider merging these comparisons with 'in' by using '%s %sin (%s)'. Use a set instead if elements are hashable.*
To check if a variable is equal to one of many values, combine the values
into a set or tuple and check if the variable is contained "in" it instead of
checking for equality against each of the values. This is faster and less
verbose.
:consider-using-get (R1715): *Consider using dict.get for getting values from a dict if a key is present or a default if not*
Using the builtin dict.get for getting a value from a dictionary if a key is
present or a default if not, is simpler and considered more idiomatic,
although sometimes a bit slower
:chained-comparison (R1716): *Simplify chained comparison between the operands: %s*
This message is emitted when pylint encounters boolean operation like "a < b
and b < c", suggesting instead to refactor it to "a < b < c"
:consider-using-dict-comprehension (R1717): *Consider using a dictionary comprehension*
Emitted when we detect the creation of a dictionary using the dict() callable
and a transient list. Although there is nothing syntactically wrong with this
code, it is hard to read and can be simplified to a dict comprehension. Also
it is faster since you don't need to create another transient list
:consider-using-set-comprehension (R1718): *Consider using a set comprehension*
Although there is nothing syntactically wrong with this code, it is hard to
read and can be simplified to a set comprehension. Also it is faster since
you don't need to create another transient list
:simplifiable-if-expression (R1719): *The if expression can be replaced with %s*
Used when an if expression can be replaced with 'bool(test)' or simply 'test'
if the boolean cast is implicit.
:no-else-raise (R1720): *Unnecessary "%s" after "raise", %s*
Used in order to highlight an unnecessary block of code following an if, or a
try/except containing a raise statement. As such, it will warn when it
encounters an else following a chain of ifs, all of them containing a raise
statement.
:unnecessary-comprehension (R1721): *Unnecessary use of a comprehension, use %s instead.*
Instead of using an identity comprehension, consider using the list, dict or
set constructor. It is faster and simpler.
:consider-using-sys-exit (R1722): *Consider using 'sys.exit' instead*
Contrary to 'exit()' or 'quit()', 'sys.exit' does not rely on the site module
being available (as the 'sys' module is always available).
:no-else-break (R1723): *Unnecessary "%s" after "break", %s*
Used in order to highlight an unnecessary block of code following an if
containing a break statement. As such, it will warn when it encounters an
else following a chain of ifs, all of them containing a break statement.
:no-else-continue (R1724): *Unnecessary "%s" after "continue", %s*
Used in order to highlight an unnecessary block of code following an if
containing a continue statement. As such, it will warn when it encounters an
else following a chain of ifs, all of them containing a continue statement.
:super-with-arguments (R1725): *Consider using Python 3 style super() without arguments*
Emitted when calling the super() builtin with the current class and instance.
On Python 3 these arguments are the default and they can be omitted.
:simplifiable-condition (R1726): *Boolean condition "%s" may be simplified to "%s"*
Emitted when a boolean condition is able to be simplified.
:condition-evals-to-constant (R1727): *Boolean condition '%s' will always evaluate to '%s'*
Emitted when a boolean condition can be simplified to a constant value.
:consider-using-generator (R1728): *Consider using a generator instead '%s(%s)'*
If your container can be large using a generator will bring better
performance.
:use-a-generator (R1729): *Use a generator instead '%s(%s)'*
Comprehension inside of 'any', 'all', 'max', 'min' or 'sum' is unnecessary. A
generator would be sufficient and faster.
:consider-using-min-builtin (R1730): *Consider using '%s' instead of unnecessary if block*
Using the min builtin instead of a conditional improves readability and
conciseness.
:consider-using-max-builtin (R1731): *Consider using '%s' instead of unnecessary if block*
Using the max builtin instead of a conditional improves readability and
conciseness.
:consider-using-with (R1732): *Consider using 'with' for resource-allocating operations*
Emitted if a resource-allocating assignment or call may be replaced by a
'with' block. By using 'with' the release of the allocated resources is
ensured even in the case of an exception.
:unnecessary-dict-index-lookup (R1733): *Unnecessary dictionary index lookup, use '%s' instead*
Emitted when iterating over the dictionary items (key-item pairs) and
accessing the value by index lookup. The value can be accessed directly
instead.
:use-list-literal (R1734): *Consider using [] instead of list()*
Emitted when using list() to create an empty list instead of the literal [].
The literal is faster as it avoids an additional function call.
:use-dict-literal (R1735): *Consider using '%s' instead of a call to 'dict'.*
Emitted when using dict() to create a dictionary instead of a literal '{ ...
}'. The literal is faster as it avoids an additional function call.
:unnecessary-list-index-lookup (R1736): *Unnecessary list index lookup, use '%s' instead*
Emitted when iterating over an enumeration and accessing the value by index
lookup. The value can be accessed directly instead.
:use-yield-from (R1737): *Use 'yield from' directly instead of yielding each element one by one*
Yielding directly from the iterator is faster and arguably cleaner code than
yielding each element one by one in the loop.
:chained-comparison-all-equal (R1738): *Simplify chained comparison cycle to equality between the operands: %s*
Emitted when the operands of a boolean condition form a cycle of weak
inequalities (``<=`` or ``>=``). The condition is equivalent to checking that
all the operands are equal.
:impossible-comparison (R1739): *This comparison always evaluates to False*
Emitted when a boolean condition contains a chain of comparisons that is
logically contradictory and can never be true (e.g. ``a > b and b > a``).
:unnecessary-negation (C0117): *Consider changing "%s" to "%s"*
Used when a boolean expression contains an unneeded negation, e.g. when two
negation operators cancel each other out.
:consider-using-enumerate (C0200): *Consider using enumerate instead of iterating with range and len*
Emitted when code that iterates with range and len is encountered. Such code
can be simplified by using the enumerate builtin.
:consider-iterating-dictionary (C0201): *Consider iterating the dictionary directly instead of calling .keys()*
Emitted when the keys of a dictionary are iterated through the ``.keys()``
method or when ``.keys()`` is used for a membership check. It is enough to
iterate through the dictionary itself, ``for key in dictionary``. For
membership checks, ``if key in dictionary`` is faster.
:consider-using-dict-items (C0206): *Consider iterating with .items()*
Emitted when iterating over the keys of a dictionary and accessing the value
by index lookup. Both the key and value can be accessed by iterating using
the .items() method of the dictionary instead.
:use-maxsplit-arg (C0207): *Use %s instead*
Emitted when accessing only the first or last element of str.split(). The
first and last element can be accessed by using str.split(sep, maxsplit=1)[0]
or str.rsplit(sep, maxsplit=1)[-1] instead.
:use-sequence-for-iteration (C0208): *Use a sequence type when iterating over values*
When iterating over values, sequence types (e.g., ``lists``, ``tuples``,
``ranges``) are more efficient than ``sets``.
:consider-using-f-string (C0209): *Formatting a regular string which could be an f-string*
Used when we detect a string that is being formatted with format() or % which
could potentially be an f-string. The use of f-strings is preferred. Requires
Python 3.6 and ``py-version >= 3.6``.
:use-implicit-booleaness-not-len (C1802): *Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty*
Empty sequences are considered false in a boolean context. You can either
remove the call to 'len' (``if not x``) or compare the length against a
scalar (``if len(x) > 1``).
:use-implicit-booleaness-not-comparison (C1803): *"%s" can be simplified to "%s", if it is strictly a sequence, as an empty %s is falsey*
Empty sequences are considered false in a boolean context. Following this
check blindly in weakly typed code base can create hard to debug issues. If
the value can be something else that is falsey but not a sequence (for
example ``None``, an empty string, or ``0``) the code will not be equivalent.
:use-implicit-booleaness-not-comparison-to-string (C1804): *"%s" can be simplified to "%s", if it is strictly a string, as an empty string is falsey*
Empty string are considered false in a boolean context. Following this check
blindly in weakly typed code base can create hard to debug issues. If the
value can be something else that is falsey but not a string (for example
``None``, an empty sequence, or ``0``) the code will not be equivalent.
:use-implicit-booleaness-not-comparison-to-zero (C1805): *"%s" can be simplified to "%s", if it is strictly an int, as 0 is falsey*
0 is considered false in a boolean context. Following this check blindly in
weakly typed code base can create hard to debug issues. If the value can be
something else that is falsey but not an int (for example ``None``, an empty
string, or an empty sequence) the code will not be equivalent.
.. _similarities-checker:
Similarities checker
~~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``similarities``.
See also :ref:`similarities checker's options' documentation <similarities-options>`
Similarities checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:duplicate-code (R0801): *Similar lines in %s files*
Indicates that a set of similar lines has been detected among multiple file.
This usually means that the code should be refactored to avoid this
duplication.
Similarities checker Reports
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:RP0801: Duplication
.. _spelling-checker:
Spelling checker
~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``spelling``.
See also :ref:`spelling checker's options' documentation <spelling-options>`
Spelling checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^
:wrong-spelling-in-comment (C0401): *Wrong spelling of a word '%s' in a comment:*
Used when a word in comment is not spelled correctly.
:wrong-spelling-in-docstring (C0402): *Wrong spelling of a word '%s' in a docstring:*
Used when a word in docstring is not spelled correctly.
:invalid-characters-in-docstring (C0403): *Invalid characters %r in a docstring*
Used when a word in docstring cannot be checked by enchant.
.. _stdlib-checker:
Stdlib checker
~~~~~~~~~~~~~~
Verbatim name of the checker is ``stdlib``.
Stdlib checker Messages
^^^^^^^^^^^^^^^^^^^^^^^
:invalid-envvar-value (E1507): *%s does not support %s type argument*
Env manipulation functions support only string type arguments. See
https://docs.python.org/3/library/os.html#os.getenv.
:singledispatch-method (E1519): *singledispatch decorator should not be used with methods, use singledispatchmethod instead.*
singledispatch should decorate functions and not class/instance methods. Use
singledispatchmethod for those cases.
:singledispatchmethod-function (E1520): *singledispatchmethod decorator should not be used with functions, use singledispatch instead.*
singledispatchmethod should decorate class/instance methods and not
functions. Use singledispatch for those cases.
:bad-open-mode (W1501): *"%s" is not a valid mode for open.*
Python supports: r, w, a[, x] modes with b, +, and U (only with r) options.
See https://docs.python.org/3/library/functions.html#open
:boolean-datetime (W1502): *Using datetime.time in a boolean context.*
Using datetime.time in a boolean context can hide subtle bugs when the time
they represent matches midnight UTC. This behaviour was fixed in Python 3.5.
See https://bugs.python.org/issue13936 for reference. This message can't be
emitted when using Python >= 3.5.
:redundant-unittest-assert (W1503): *Redundant use of %s with constant value %r*
The first argument of assertTrue and assertFalse is a condition. If a
constant is passed as parameter, that condition will be always true. In this
case a warning should be emitted. The same applies to assertEqual and
assertNotEqual when both compared values are constants.
:bad-thread-instantiation (W1506): *threading.Thread needs the target function*
The warning is emitted when a threading.Thread class is instantiated without
the target function being passed as a kwarg or as a second argument. By
default, the first parameter is the group param, not the target param.
:shallow-copy-environ (W1507): *Using copy.copy(os.environ). Use os.environ.copy() instead.*
os.environ is not a dict object but proxy object, so shallow copy has still
effects on original object. See https://bugs.python.org/issue15373 for
reference.
:invalid-envvar-default (W1508): *%s default type is %s. Expected str or None.*
Env manipulation functions return None or str values. Supplying anything
different as a default may cause bugs. See
https://docs.python.org/3/library/os.html#os.getenv.
:subprocess-popen-preexec-fn (W1509): *Using preexec_fn keyword which may be unsafe in the presence of threads*
The preexec_fn parameter is not safe to use in the presence of threads in
your application. The child process could deadlock before exec is called. If
you must use it, keep it trivial! Minimize the number of libraries you call
into. See https://docs.python.org/3/library/subprocess.html#popen-constructor
:subprocess-run-check (W1510): *'subprocess.run' used without explicitly defining the value for 'check'.*
The ``check`` keyword is set to False by default. It means the process
launched by ``subprocess.run`` can exit with a non-zero exit code and fail
silently. It's better to set it explicitly to make clear what the error-
handling behavior is.
:unspecified-encoding (W1514): *Using open without explicitly specifying an encoding*
It is better to specify an encoding when opening documents. Using the system
default implicitly can create problems on other operating systems. See
https://peps.python.org/pep-0597/ This message can't be emitted when using
Python >= 3.15.
:forgotten-debug-statement (W1515): *Leaving functions creating breakpoints in production code is not recommended*
Calls to breakpoint(), sys.breakpointhook() and pdb.set_trace() should be
removed from code that is not actively being debugged.
:method-cache-max-size-none (W1518): *'lru_cache(maxsize=None)' or 'cache' will keep all method args alive indefinitely, including 'self'*
By decorating a method with lru_cache or cache the 'self' argument will be
linked to the function and therefore never garbage collected. Unless your
instance will never need to be garbage collected (singleton) it is
recommended to refactor code to avoid this pattern or add a maxsize to the
cache. The default value for maxsize is 128.
:deprecated-method (W4902): *Using deprecated method %s()*
The method is marked as deprecated and will be removed in the future.
:deprecated-argument (W4903): *Using deprecated argument %s of method %s()*
The argument is marked as deprecated and will be removed in the future.
:deprecated-class (W4904): *Using deprecated class %s of module %s*
The class is marked as deprecated and will be removed in the future.
:deprecated-decorator (W4905): *Using deprecated decorator %s()*
The decorator is marked as deprecated and will be removed in the future.
:deprecated-attribute (W4906): *Using deprecated attribute %r*
The attribute is marked as deprecated and will be removed in the future.
.. _string-checker:
String checker
~~~~~~~~~~~~~~
Verbatim name of the checker is ``string``.
See also :ref:`string checker's options' documentation <string-options>`
String checker Messages
^^^^^^^^^^^^^^^^^^^^^^^
:bad-format-character (E1300): *Unsupported format character %r (%#02x) at index %d*
Used when an unsupported format character is used in a format string.
:truncated-format-string (E1301): *Format string ends in middle of conversion specifier*
Used when a format string terminates before the end of a conversion
specifier.
:mixed-format-string (E1302): *Mixing named and unnamed conversion specifiers in format string*
Used when a format string contains both named (e.g. '%(foo)d') and unnamed
(e.g. '%d') conversion specifiers. This is also used when a named conversion
specifier contains * for the minimum field width and/or precision.
:format-needs-mapping (E1303): *Expected mapping for format string, not %s*
Used when a format string that uses named conversion specifiers is used with
an argument that is not a mapping.
:missing-format-string-key (E1304): *Missing key %r in format string dictionary*
Used when a format string that uses named conversion specifiers is used with
a dictionary that doesn't contain all the keys required by the format string.
:too-many-format-args (E1305): *Too many arguments for format string*
Used when a format string that uses unnamed conversion specifiers is given
too many arguments.
:too-few-format-args (E1306): *Not enough arguments for format string*
Used when a format string that uses unnamed conversion specifiers is given
too few arguments
:bad-string-format-type (E1307): *Argument %r does not match format type %r*
Used when a type required by format string is not suitable for actual
argument type
:bad-str-strip-call (E1310): *Suspicious argument in %s.%s call*
The argument to a str.{l,r,}strip call contains a duplicate character,
:bad-format-string-key (W1300): *Format string dictionary key should be a string, not %s*
Used when a format string that uses named conversion specifiers is used with
a dictionary whose keys are not all strings.
:unused-format-string-key (W1301): *Unused key %r in format string dictionary*
Used when a format string that uses named conversion specifiers is used with
a dictionary that contains keys not required by the format string.
:bad-format-string (W1302): *Invalid format string*
Used when a PEP 3101 format string is invalid.
:missing-format-argument-key (W1303): *Missing keyword argument %r for format string*
Used when a PEP 3101 format string that uses named fields doesn't receive one
or more required keywords.
:unused-format-string-argument (W1304): *Unused format argument %r*
Used when a PEP 3101 format string that uses named fields is used with an
argument that is not required by the format string.
:format-combined-specification (W1305): *Format string contains both automatic field numbering and manual field specification*
Used when a PEP 3101 format string contains both automatic field numbering
(e.g. '{}') and manual field specification (e.g. '{0}').
:missing-format-attribute (W1306): *Missing format attribute %r in format specifier %r*
Used when a PEP 3101 format string uses an attribute specifier ({0.length}),
but the argument passed for formatting doesn't have that attribute.
:invalid-format-index (W1307): *Using invalid lookup key %r in format specifier %r*
Used when a PEP 3101 format string uses a lookup specifier ({a[1]}), but the
argument passed for formatting doesn't contain or doesn't have that key as an
attribute.
:duplicate-string-formatting-argument (W1308): *Duplicate string formatting argument %r, consider passing as named argument*
Used when we detect that a string formatting is repeating an argument instead
of using named string arguments
:f-string-without-interpolation (W1309): *Using an f-string that does not have any interpolated variables*
Used when we detect an f-string that does not use any interpolation
variables, in which case it can be either a normal string or a bug in the
code.
:format-string-without-interpolation (W1310): *Using formatting for a string that does not have any interpolated variables*
Used when we detect a string that does not have any interpolation variables,
in which case it can be either a normal string without formatting or a bug in
the code.
:anomalous-backslash-in-string (W1401): *Anomalous backslash in string: '%s'. String constant might be missing an r prefix.*
Used when a backslash is in a literal string but not as an escape.
:anomalous-unicode-escape-in-string (W1402): *Anomalous Unicode escape in byte string: '%s'. String constant might be missing an r or u prefix.*
Used when an escape like \u is encountered in a byte string where it has no
effect.
:implicit-str-concat (W1404): *Implicit string concatenation found in %s*
String literals are implicitly concatenated in a literal iterable definition
: maybe a comma is missing ?
:inconsistent-quotes (W1405): *Quote delimiter %s is inconsistent with the rest of the file*
Quote delimiters are not used consistently throughout a module (with
allowances made for avoiding unnecessary escaping).
:redundant-u-string-prefix (W1406): *The u prefix for strings is no longer necessary in Python >=3.0*
Used when we detect a string with a u prefix. These prefixes were necessary
in Python 2 to indicate a string was Unicode, but since Python 3.0 strings
are Unicode by default.
.. _threading-checker:
Threading checker
~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``threading``.
Threading checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^
:useless-with-lock (W2101): *'%s()' directly created in 'with' has no effect*
Used when a new lock instance is created by using with statement which has no
effect. Instead, an existing instance should be used to acquire lock.
.. _typecheck-checker:
Typecheck checker
~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``typecheck``.
See also :ref:`typecheck checker's options' documentation <typecheck-options>`
Typecheck checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^
:no-member (E1101): *%s %r has no %r member%s*
Used when a variable is accessed for a nonexistent member.
:not-callable (E1102): *%s is not callable*
Used when an object being called has been inferred to a non callable object.
:assignment-from-no-return (E1111): *Assigning result of a function call, but %r returns None%s*
Used when an assignment is done on a function call but the inferred function
doesn't return anything.
:no-value-for-parameter (E1120): *No value for argument %s in %s call*
Used when a function call passes too few arguments.
:too-many-function-args (E1121): *Too many positional arguments for %s call*
Used when a function call passes too many positional arguments.
:unexpected-keyword-arg (E1123): *Unexpected keyword argument %r in %s call*
Used when a function call passes a keyword argument that doesn't correspond
to one of the function's parameter names.
:redundant-keyword-arg (E1124): *Argument %r passed by position and keyword in %s call*
Used when a function call would result in assigning multiple values to a
function parameter, one value from a positional argument and one from a
keyword argument.
:missing-kwoa (E1125): *Missing mandatory keyword argument %r in %s call*
Used when a function call does not pass a mandatory keyword-only argument.
:invalid-sequence-index (E1126): *Sequence index is not an int, slice, or instance with __index__*
Used when a sequence type is indexed with an invalid type. Valid types are
ints, slices, and objects with an __index__ method.
:invalid-slice-index (E1127): *Slice index is not an int, None, or instance with __index__*
Used when a slice index is not an integer, None, or an object with an
__index__ method.
:assignment-from-none (E1128): *Assigning result of a function call, where the function returns None*
Used when an assignment is done on a function call but the inferred function
returns nothing but None.
:not-context-manager (E1129): *Context manager '%s' doesn't implement __enter__ and __exit__.*
Used when an instance in a with statement doesn't implement the context
manager protocol(__enter__/__exit__).
:invalid-unary-operand-type (E1130):
Emitted when a unary operand is used on an object which does not support this
type of operation.
:unsupported-binary-operation (E1131):
Emitted when a binary arithmetic operation between two operands is not
supported.
:repeated-keyword (E1132): *Got multiple values for keyword argument %r in function call*
Emitted when a function call got multiple values for a keyword.
:not-an-iterable (E1133): *Non-iterable value %s is used in an iterating context*
Used when a non-iterable value is used in place where iterable is expected
:not-a-mapping (E1134): *Non-mapping value %s is used in a mapping context*
Used when a non-mapping value is used in place where mapping is expected
:unsupported-membership-test (E1135): *Value '%s' doesn't support membership test*
Emitted when an instance in membership test expression doesn't implement
membership protocol (__contains__/__iter__/__getitem__).
:unsubscriptable-object (E1136): *Value '%s' is unsubscriptable*
Emitted when a subscripted value doesn't support subscription (i.e. doesn't
define __getitem__ method or __class_getitem__ for a class).
:unsupported-assignment-operation (E1137): *%r does not support item assignment*
Emitted when an object does not support item assignment (i.e. doesn't define
__setitem__ method).
:unsupported-delete-operation (E1138): *%r does not support item deletion*
Emitted when an object does not support item deletion (i.e. doesn't define
__delitem__ method).
:invalid-metaclass (E1139): *Invalid metaclass %r used*
Emitted whenever we can detect that a class is using, as a metaclass,
something which might be invalid for using as a metaclass.
:dict-iter-missing-items (E1141): *Unpacking a dictionary in iteration without calling .items()*
Emitted when trying to iterate through a dict without calling .items()
:await-outside-async (E1142): *'await' should be used within an async function*
Emitted when await is used outside an async function.
:unhashable-member (E1143): *'%s' is unhashable and can't be used as a %s in a %s*
Emitted when a dict key or set member is not hashable (i.e. doesn't define
__hash__ method).
:invalid-slice-step (E1144): *Slice step cannot be 0*
Used when a slice step is 0 and the object doesn't implement a custom
__getitem__ method.
:async-context-manager-with-regular-with (E1145): *Context manager '%s' is async and should be used with 'async with'.*
Used when an async context manager is used with a regular 'with' statement
instead of 'async with'.
:keyword-arg-before-vararg (W1113): *Keyword argument before variable positional arguments list in the definition of %s function*
When defining a keyword argument before variable positional arguments, one
can end up in having multiple values passed for the aforementioned parameter
in case the method is called with keyword arguments.
:arguments-out-of-order (W1114): *Positional arguments appear to be out of order*
Emitted when the caller's argument names fully match the parameter names in
the function signature but do not have the same order.
:non-str-assignment-to-dunder-name (W1115): *Non-string value assigned to __name__*
Emitted when a non-string value is assigned to __name__
:isinstance-second-argument-not-valid-type (W1116): *Second argument of isinstance is not a type*
Emitted when the second argument of an isinstance call is not a type.
:kwarg-superseded-by-positional-arg (W1117): *%r will be included in %r since a positional-only parameter with this name already exists*
Emitted when a function is called with a keyword argument that has the same
name as a positional-only parameter and the function contains a keyword
variadic parameter dict.
:c-extension-no-member (I1101): *%s %r has no %r member%s, but source is unavailable. Consider adding this module to extension-pkg-allow-list if you want to perform analysis based on run-time introspection of living objects.*
Used when a variable is accessed for non-existent member of C extension. Due
to unavailability of source static analysis is impossible, but it may be
performed by introspecting living objects in run-time.
.. _unicode_checker-checker:
Unicode Checker checker
~~~~~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``unicode_checker``.
Unicode Checker checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:invalid-unicode-codec (E2501): *UTF-16 and UTF-32 aren't backward compatible. Use UTF-8 instead*
For compatibility use UTF-8 instead of UTF-16/UTF-32. See also
https://bugs.python.org/issue1503789 for a history of this issue. And
https://softwareengineering.stackexchange.com/questions/102205/ for some
possible problems when using UTF-16 for instance.
:bidirectional-unicode (E2502): *Contains control characters that can permit obfuscated code executed differently than displayed*
bidirectional unicode are typically not displayed characters required to
display right-to-left (RTL) script (i.e. Chinese, Japanese, Arabic, Hebrew,
...) correctly. So can you trust this code? Are you sure it displayed
correctly in all editors? If you did not write it or your language is not
RTL, remove the special characters, as they could be used to trick you into
executing code, that does something else than what it looks like. More
Information: https://en.wikipedia.org/wiki/Bidirectional_text
https://trojansource.codes/
:invalid-character-backspace (E2510): *Invalid unescaped character backspace, use "\b" instead.*
Moves the cursor back, so the character after it will overwrite the character
before.
:invalid-character-carriage-return (E2511): *Invalid unescaped character carriage-return, use "\r" instead.*
Moves the cursor to the start of line, subsequent characters overwrite the
start of the line.
:invalid-character-sub (E2512): *Invalid unescaped character sub, use "\x1A" instead.*
Ctrl+Z "End of text" on Windows. Some programs (such as type) ignore the rest
of the file after it.
:invalid-character-esc (E2513): *Invalid unescaped character esc, use "\x1B" instead.*
Commonly initiates escape codes which allow arbitrary control of the
terminal.
:invalid-character-nul (E2514): *Invalid unescaped character nul, use "\0" instead.*
Mostly end of input for python.
:invalid-character-zero-width-space (E2515): *Invalid unescaped character zero-width-space, use "\u200B" instead.*
Invisible space character could hide real code execution.
:bad-file-encoding (C2503): *PEP8 recommends UTF-8 as encoding for Python files*
PEP8 recommends UTF-8 default encoding for Python files. See
https://peps.python.org/pep-0008/#source-file-encoding
.. _unnecessary-dunder-call-checker:
Unnecessary-Dunder-Call checker
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``unnecessary-dunder-call``.
Unnecessary-Dunder-Call checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:unnecessary-dunder-call (C2801): *Unnecessarily calls dunder method %s. %s.*
Used when a dunder method is manually called instead of using the
corresponding function/method/operator.
.. _unnecessary_ellipsis-checker:
Unnecessary Ellipsis checker
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``unnecessary_ellipsis``.
Unnecessary Ellipsis checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:unnecessary-ellipsis (W2301): *Unnecessary ellipsis constant*
Used when the ellipsis constant is encountered and can be avoided. A line of
code consisting of an ellipsis is unnecessary if there is a docstring on the
preceding line or if there is a statement in the same scope.
.. _unsupported_version-checker:
Unsupported Version checker
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``unsupported_version``.
Unsupported Version checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:using-f-string-in-unsupported-version (W2601): *F-strings are not supported by all versions included in the py-version setting*
Used when the py-version set by the user is lower than 3.6 and pylint
encounters an f-string.
:using-final-decorator-in-unsupported-version (W2602): *typing.final is not supported by all versions included in the py-version setting*
Used when the py-version set by the user is lower than 3.8 and pylint
encounters a ``typing.final`` decorator.
:using-exception-groups-in-unsupported-version (W2603): *Exception groups are not supported by all versions included in the py-version setting*
Used when the py-version set by the user is lower than 3.11 and pylint
encounters ``except*`` or `ExceptionGroup``.
:using-generic-type-syntax-in-unsupported-version (W2604): *Generic type syntax (PEP 695) is not supported by all versions included in the py-version setting*
Used when the py-version set by the user is lower than 3.12 and pylint
encounters generic type syntax.
:using-assignment-expression-in-unsupported-version (W2605): *Assignment expression is not supported by all versions included in the py-version setting*
Used when the py-version set by the user is lower than 3.8 and pylint
encounters an assignment expression (walrus) operator.
:using-positional-only-args-in-unsupported-version (W2606): *Positional-only arguments are not supported by all versions included in the py-version setting*
Used when the py-version set by the user is lower than 3.8 and pylint
encounters positional-only arguments.
:using-comprehension-unpacking-in-unsupported-version (W2607): *Unpacking in comprehensions is not supported by all versions included in the py-version setting*
Used when the py-version set by the user is lower than 3.15 and pylint
encounters the ``*`` or ``**`` unpacking added by PEP 798 in a comprehension.
:using-lazy-import-in-unsupported-version (W2608): *Lazy imports are not supported by all versions included in the py-version setting*
Used when the py-version set by the user is lower than 3.15 and pylint
encounters the ``lazy`` import added by PEP 810.
.. _variables-checker:
Variables checker
~~~~~~~~~~~~~~~~~
Verbatim name of the checker is ``variables``.
See also :ref:`variables checker's options' documentation <variables-options>`
Variables checker Messages
^^^^^^^^^^^^^^^^^^^^^^^^^^
:used-before-assignment (E0601): *Using variable %r before assignment*
Emitted when a local variable is accessed before its assignment took place.
Assignments in try blocks are assumed not to have occurred when evaluating
associated except/finally blocks. Assignments in except blocks are assumed
not to have occurred when evaluating statements outside the block, except
when the associated try block contains a return statement.
:undefined-variable (E0602): *Undefined variable %r*
Used when an undefined variable is accessed.
:undefined-all-variable (E0603): *Undefined variable name %r in __all__*
Used when an undefined variable name is referenced in __all__.
:invalid-all-object (E0604): *Invalid object %r in __all__, must contain only strings*
Used when an invalid (non-string) object occurs in __all__.
:invalid-all-format (E0605): *Invalid format for __all__, must be tuple or list*
Used when __all__ has an invalid format.
:possibly-used-before-assignment (E0606): *Possibly using variable %r before assignment*
Emitted when a local variable is accessed before its assignment took place in
both branches of an if/else switch.
:no-name-in-module (E0611): *No name %r in module %r*
Used when a name cannot be found in a module.
:unpacking-non-sequence (E0633): *Attempting to unpack a non-sequence%s*
Used when something which is not a sequence is used in an unpack assignment
:potential-index-error (E0643): *Invalid index for iterable length*
Emitted when an index used on an iterable goes beyond the length of that
iterable.
:global-variable-undefined (W0601): *Global variable %r undefined at the module level*
Used when a variable is defined through the "global" statement but the
variable is not defined in the module scope.
:global-variable-not-assigned (W0602): *Using global for %r but no assignment is done*
When a variable defined in the global scope is modified in an inner scope,
the 'global' keyword is required in the inner scope only if there is an
assignment operation done in the inner scope.
:global-statement (W0603): *Using the global statement*
Used when you use the "global" statement to update a global variable. Pylint
discourages its usage. That doesn't mean you cannot use it!
:global-at-module-level (W0604): *Using the global statement at the module level*
Used when you use the "global" statement at the module level since it has no
effect.
:unused-import (W0611): *Unused %s*
Used when an imported module or variable is not used.
:unused-variable (W0612): *Unused variable %r*
Used when a variable is defined but not used.
:unused-argument (W0613): *Unused argument %r*
Used when a function or method argument is not used.
:unused-wildcard-import (W0614): *Unused import(s) %s from wildcard import of %s*
Used when an imported module or variable is not used from a `'from X import
*'` style import.
:redefined-outer-name (W0621): *Redefining name %r from outer scope (line %s)*
Used when a variable's name hides a name defined in an outer scope or except
handler.
:redefined-builtin (W0622): *Redefining built-in %r*
Used when a variable or function override a built-in.
:undefined-loop-variable (W0631): *Using possibly undefined loop variable %r*
Used when a loop variable (i.e. defined by a for loop or a list comprehension
or a generator expression) is used outside the loop.
:unbalanced-tuple-unpacking (W0632): *Possible unbalanced tuple unpacking with sequence %s: left side has %d label%s, right side has %d value%s*
Used when there is an unbalanced tuple unpacking in assignment
:cell-var-from-loop (W0640): *Cell variable %s defined in loop*
A variable used in a closure is defined in a loop. This will result in all
closures using the same value for the closed-over variable.
:possibly-unused-variable (W0641): *Possibly unused variable %r*
Used when a variable is defined but might not be used. The possibility comes
from the fact that locals() might be used, which could consume or not the
said variable
:self-cls-assignment (W0642): *Invalid assignment to %s in method*
Invalid assignment to self or cls in instance or class method respectively.
:unbalanced-dict-unpacking (W0644): *Possible unbalanced dict unpacking with %s: left side has %d label%s, right side has %d value%s*
Used when there is an unbalanced dict unpacking in assignment or for loop
---
### Doc User Guide Checkers Index (`doc/user_guide/checkers/index.rst`)
Checkers
========
.. toctree::
:maxdepth: 2
:titlesonly:
:hidden:
features
extensions
---
### Doc User Guide Configuration All Options (`doc/user_guide/configuration/all-options.rst`)
.. This file is auto-generated. Make any changes to the associated
.. docs extension in 'doc/exts/pylint_options.py'.
.. _all-options:
Standard Checkers
^^^^^^^^^^^^^^^^^
.. _main-options:
``Main`` **Checker**
--------------------
.. _analyse-fallback-blocks-option:
--analyse-fallback-blocks
"""""""""""""""""""""""""
*Analyse import fallback blocks. This can be used to support both Python 2 and 3 compatible code, which means that the block might have code that exists only in one or another interpreter, leading to false positives when analysed.*
**Default:** ``False``
.. _clear-cache-post-run-option:
--clear-cache-post-run
""""""""""""""""""""""
*Clear in-memory caches upon conclusion of linting. Useful if running pylint in a server-like mode.*
**Default:** ``False``
.. _confidence-option:
--confidence
""""""""""""
*Only show warnings with the listed confidence levels. Leave empty to show all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, UNDEFINED.*
**Default:** ``['HIGH', 'CONTROL_FLOW', 'INFERENCE', 'INFERENCE_FAILURE', 'UNDEFINED']``
.. _disable-option:
--disable
"""""""""
*Disable the message, report, category or checker with the given id(s). You can either give multiple identifiers separated by comma (,) or put this option multiple times (only on the command line, not in the configuration file where it should appear only once). You can also use "--disable=all" to disable everything first and then re-enable specific checks. For example, if you want to run only the similarities checker, you can use "--disable=all --enable=similarities". If you want to run only the classes checker, but have no Warning level messages displayed, use "--disable=all --enable=classes --disable=W".*
**Default:** ``()``
.. _enable-option:
--enable
""""""""
*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 (only on the command line, not in the configuration file where it should appear only once). See also the "--disable" option for examples.*
**Default:** ``()``
.. _enable-all-extensions-option:
--enable-all-extensions
"""""""""""""""""""""""
*Load and enable all available extensions. Use --list-extensions to see a list all available extensions.*
**Default:** ``None``
**This option is only available on the command line.**
.. _errors-only-option:
--errors-only
"""""""""""""
*In error mode, messages with a category besides ERROR or FATAL are suppressed, and no reports are done by default. Error mode is compatible with disabling specific errors.*
**Default:** ``None``
**This option is only available on the command line.**
.. _evaluation-option:
--evaluation
""""""""""""
*Python expression which should return a score less than or equal to 10. You have access to the variables 'fatal', 'error', 'warning', 'refactor', 'convention', and 'info' which contain the number of messages in each category, as well as 'statement' which is the total number of statements analyzed. This score is used by the global evaluation report (RP0004).*
**Default:** ``max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))``
.. _exit-zero-option:
--exit-zero
"""""""""""
*Always return a 0 (non-error) status code, even if lint errors are found. This is primarily useful in continuous integration scripts.*
**Default:** ``False``
.. _extension-pkg-allow-list-option:
--extension-pkg-allow-list
""""""""""""""""""""""""""
*A comma-separated list of package or module names from where C extensions may be loaded. Extensions are loading into the active Python interpreter and may run arbitrary code.*
**Default:** ``[]``
.. _extension-pkg-whitelist-option:
--extension-pkg-whitelist
"""""""""""""""""""""""""
*A comma-separated list of package or module names from where C extensions may be loaded. Extensions are loading into the active Python interpreter and may run arbitrary code. (This is an alternative name to extension-pkg-allow-list for backward compatibility.)*
**Default:** ``[]``
.. _fail-on-option:
--fail-on
"""""""""
*Return non-zero exit code if any of these messages/categories are detected, even if score is above --fail-under value. Syntax same as enable. Messages specified are enabled, while categories only check already-enabled messages.*
**Default:** ``""``
.. _fail-under-option:
--fail-under
""""""""""""
*Specify a score threshold under which the program will exit with error.*
**Default:** ``10``
.. _files-option:
--files
"""""""
*The files to lint. The flag can also be omitted as pylint will try to lint any file passed as argument. This can be used to set files to a directory in a configuration file and invoke pylint by only typing pylint on the command line. Any file passed as argument will overwrite any file set in the configuration file.*
**Default:** ``[]``
.. _from-stdin-option:
--from-stdin
""""""""""""
*Interpret the stdin as a python script, whose filename needs to be passed as the module_or_package argument.*
**Default:** ``False``
.. _full-documentation-option:
--full-documentation
""""""""""""""""""""
*Generate pylint's full documentation.*
**Default:** ``None``
**This option is only available on the command line.**
.. _generate-rcfile-option:
--generate-rcfile
"""""""""""""""""
*Generate a sample configuration file according to the current configuration. You can put other options before this one to get them in the generated configuration.*
**Default:** ``None``
**This option is only available on the command line.**
.. _generate-toml-config-option:
--generate-toml-config
""""""""""""""""""""""
*Generate a sample configuration file according to the current configuration. You can put other options before this one to get them in the generated configuration. The config is in the .toml format.*
**Default:** ``None``
**This option is only available on the command line.**
.. _help-msg-option:
--help-msg
""""""""""
*Display a help message for the given message id and exit. The value may be a comma separated list of message ids.*
**Default:** ``None``
**This option is only available on the command line.**
.. _ignore-option:
--ignore
""""""""
*Files or directories to be skipped. They should be base names, not paths.*
**Default:** ``('CVS',)``
.. _ignore-paths-option:
--ignore-paths
""""""""""""""
*Add files or directories matching the regular expressions patterns to the ignore-list. The regex matches against paths and can be in Posix or Windows format. Because '\\' represents the directory delimiter on Windows systems, it can't be used as an escape character.*
**Default:** ``[]``
.. _ignore-patterns-option:
--ignore-patterns
"""""""""""""""""
*Files or directories matching the regular expression patterns are skipped. The regex matches against base names, not paths. The default value ignores Emacs file locks*
**Default:** ``(re.compile('^\\.#'),)``
.. _ignored-modules-option:
--ignored-modules
"""""""""""""""""
*List of module names for which member attributes should not be checked and will not be imported (useful for modules/projects where namespaces are manipulated during runtime and thus existing member attributes cannot be deduced by static analysis). It supports qualified module names, as well as Unix pattern matching.*
**Default:** ``()``
.. _init-hook-option:
--init-hook
"""""""""""
*Python code to execute, usually for sys.path manipulation such as pygtk.require().*
**Default:** ``None``
.. _jobs-option:
--jobs
""""""
*Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the number of processors available to use, and will cap the count on Windows to avoid hangs.*
**Default:** ``1``
.. _limit-inference-results-option:
--limit-inference-results
"""""""""""""""""""""""""
*Control the amount of potential inferred values when inferring a single object. This can help the performance when dealing with large functions or complex, nested conditions.*
**Default:** ``100``
.. _list-conf-levels-option:
--list-conf-levels
""""""""""""""""""
*Generate pylint's confidence levels.*
**Default:** ``None``
**This option is only available on the command line.**
.. _list-extensions-option:
--list-extensions
"""""""""""""""""
*List available extensions.*
**Default:** ``None``
**This option is only available on the command line.**
.. _list-groups-option:
--list-groups
"""""""""""""
*List pylint's message groups.*
**Default:** ``None``
**This option is only available on the command line.**
.. _list-msgs-option:
--list-msgs
"""""""""""
*Display a list of all pylint's messages divided by whether they are emittable with the given interpreter.*
**Default:** ``None``
**This option is only available on the command line.**
.. _list-msgs-enabled-option:
--list-msgs-enabled
"""""""""""""""""""
*Display a list of what messages are enabled, disabled and non-emittable with the given configuration.*
**Default:** ``None``
**This option is only available on the command line.**
.. _load-plugins-option:
--load-plugins
""""""""""""""
*List of plugins (as comma separated values of python module names) to load, usually to register additional checkers.*
**Default:** ``()``
.. _long-help-option:
--long-help
"""""""""""
*Show more verbose help.*
**Default:** ``None``
**This option is only available on the command line.**
.. _msg-template-option:
--msg-template
""""""""""""""
*Template used to display messages. This is a python new-style format string used to format the message information. See doc for all details.*
**Default:** ``""``
.. _output-option:
--output
""""""""
*Specify an output file.*
**Default:** ``None``
**This option is only available on the command line.**
.. _output-format-option:
--output-format
"""""""""""""""
*Set the output format. Available formats are: 'text', 'no-header' (text without module headers), 'parseable', 'colorized', 'json2' (improved json format), 'json' (old json format), 'msvs' (visual studio), 'github' (GitHub actions) and 'junit' (JUnit XML). You can also give a reporter class, e.g. mypackage.mymodule.MyReporterClass.*
**Default:** ``text``
.. _persistent-option:
--persistent
""""""""""""
*Pickle collected data for later comparisons.*
**Default:** ``True``
.. _prefer-stubs-option:
--prefer-stubs
""""""""""""""
*Resolve imports to .pyi stubs if available. May reduce no-member messages and increase not-an-iterable messages.*
**Default:** ``False``
.. _py-version-option:
--py-version
""""""""""""
*Minimum Python version to use for version dependent checks. Will default to the version used to run pylint.*
**Default:** ``sys.version_info[:2]``
.. _rcfile-option:
--rcfile
""""""""
*Specify a configuration file to load.*
**Default:** ``None``
**This option is only available on the command line.**
.. _recursive-option:
--recursive
"""""""""""
*Discover python modules and packages in the file system subtree.*
**Default:** ``False``
.. _reports-option:
--reports
"""""""""
*Tells whether to display a full report or only the messages.*
**Default:** ``False``
.. _score-option:
--score
"""""""
*Activate the evaluation score.*
**Default:** ``True``
.. _source-roots-option:
--source-roots
""""""""""""""
*Add paths to the list of the source roots. Supports globbing patterns. The source root is an absolute path or a path relative to the current working directory used to determine a package namespace for modules located under the source root.*
**Default:** ``()``
.. _unsafe-load-any-extension-option:
--unsafe-load-any-extension
"""""""""""""""""""""""""""
*Allow loading of arbitrary C extensions. Extensions are imported into the active Python interpreter and may run arbitrary code.*
**Default:** ``False``
.. _verbose-option:
--verbose
"""""""""
*In verbose mode, extra non-checker-related info will be displayed.*
**Default:** ``None``
**This option is only available on the command line.**
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.main]
analyse-fallback-blocks = false
clear-cache-post-run = false
confidence = ["HIGH", "CONTROL_FLOW", "INFERENCE", "INFERENCE_FAILURE", "UNDEFINED"]
disable = ["bad-inline-option", "consider-using-augmented-assign", "deprecated-pragma", "file-ignored", "locally-disabled", "prefer-typing-namedtuple", "raw-checker-failed", "suppressed-message", "use-implicit-booleaness-not-comparison-to-string", "use-implicit-booleaness-not-comparison-to-zero", "use-symbolic-message-instead", "useless-suppression"]
enable = []
evaluation = "max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))"
exit-zero = false
extension-pkg-allow-list = []
extension-pkg-whitelist = []
fail-on = []
fail-under = 10
files = []
from-stdin = false
ignore = ["CVS"]
ignore-paths = []
ignore-patterns = ["^\\.#"]
ignored-modules = []
# init-hook =
jobs = 1
limit-inference-results = 100
load-plugins = []
msg-template = ""
# output-format =
persistent = true
prefer-stubs = false
py-version = "sys.version_info[:2]"
recursive = false
reports = false
score = true
source-roots = []
unsafe-load-any-extension = false
.. raw:: html
</details>
.. _basic-options:
``Basic`` **Checker**
---------------------
.. _argument-naming-style-option:
--argument-naming-style
"""""""""""""""""""""""
*Naming style matching correct argument names.*
**Default:** ``snake_case``
.. _argument-rgx-option:
--argument-rgx
""""""""""""""
*Regular expression matching correct argument names. Overrides argument-naming-style. If left empty, argument names will be checked with the set naming style.*
**Default:** ``None``
.. _attr-naming-style-option:
--attr-naming-style
"""""""""""""""""""
*Naming style matching correct attribute names.*
**Default:** ``snake_case``
.. _attr-rgx-option:
--attr-rgx
""""""""""
*Regular expression matching correct attribute names. Overrides attr-naming-style. If left empty, attribute names will be checked with the set naming style.*
**Default:** ``None``
.. _bad-names-option:
--bad-names
"""""""""""
*Bad variable names which should always be refused, separated by a comma.*
**Default:** ``('foo', 'bar', 'baz', 'toto', 'tutu', 'tata')``
.. _bad-names-rgxs-option:
--bad-names-rgxs
""""""""""""""""
*Bad variable names regexes, separated by a comma. If names match any regex, they will always be refused*
**Default:** ``""``
.. _class-attribute-naming-style-option:
--class-attribute-naming-style
""""""""""""""""""""""""""""""
*Naming style matching correct class attribute names.*
**Default:** ``any``
.. _class-attribute-rgx-option:
--class-attribute-rgx
"""""""""""""""""""""
*Regular expression matching correct class attribute names. Overrides class-attribute-naming-style. If left empty, class attribute names will be checked with the set naming style.*
**Default:** ``None``
.. _class-const-naming-style-option:
--class-const-naming-style
""""""""""""""""""""""""""
*Naming style matching correct class constant names.*
**Default:** ``UPPER_CASE``
.. _class-const-rgx-option:
--class-const-rgx
"""""""""""""""""
*Regular expression matching correct class constant names. Overrides class-const-naming-style. If left empty, class constant names will be checked with the set naming style.*
**Default:** ``None``
.. _class-naming-style-option:
--class-naming-style
""""""""""""""""""""
*Naming style matching correct class names.*
**Default:** ``PascalCase``
.. _class-rgx-option:
--class-rgx
"""""""""""
*Regular expression matching correct class names. Overrides class-naming-style. If left empty, class names will be checked with the set naming style.*
**Default:** ``None``
.. _const-naming-style-option:
--const-naming-style
""""""""""""""""""""
*Naming style matching correct constant names.*
**Default:** ``UPPER_CASE``
.. _const-rgx-option:
--const-rgx
"""""""""""
*Regular expression matching correct constant names. Overrides const-naming-style. If left empty, constant names will be checked with the set naming style.*
**Default:** ``None``
.. _docstring-min-length-option:
--docstring-min-length
""""""""""""""""""""""
*Minimum line length for functions/classes that require docstrings, shorter ones are exempt.*
**Default:** ``-1``
.. _function-naming-style-option:
--function-naming-style
"""""""""""""""""""""""
*Naming style matching correct function names.*
**Default:** ``snake_case``
.. _function-rgx-option:
--function-rgx
""""""""""""""
*Regular expression matching correct function names. Overrides function-naming-style. If left empty, function names will be checked with the set naming style.*
**Default:** ``None``
.. _good-names-option:
--good-names
""""""""""""
*Good variable names which should always be accepted, separated by a comma.*
**Default:** ``('i', 'j', 'k', 'ex', 'Run', '_')``
.. _good-names-rgxs-option:
--good-names-rgxs
"""""""""""""""""
*Good variable names regexes, separated by a comma. If names match any regex, they will always be accepted*
**Default:** ``""``
.. _include-naming-hint-option:
--include-naming-hint
"""""""""""""""""""""
*Include a hint for the correct naming format with invalid-name.*
**Default:** ``False``
.. _inlinevar-naming-style-option:
--inlinevar-naming-style
""""""""""""""""""""""""
*Naming style matching correct inline iteration names.*
**Default:** ``any``
.. _inlinevar-rgx-option:
--inlinevar-rgx
"""""""""""""""
*Regular expression matching correct inline iteration names. Overrides inlinevar-naming-style. If left empty, inline iteration names will be checked with the set naming style.*
**Default:** ``None``
.. _method-naming-style-option:
--method-naming-style
"""""""""""""""""""""
*Naming style matching correct method names.*
**Default:** ``snake_case``
.. _method-rgx-option:
--method-rgx
""""""""""""
*Regular expression matching correct method names. Overrides method-naming-style. If left empty, method names will be checked with the set naming style.*
**Default:** ``None``
.. _module-naming-style-option:
--module-naming-style
"""""""""""""""""""""
*Naming style matching correct module names.*
**Default:** ``snake_case``
.. _module-rgx-option:
--module-rgx
""""""""""""
*Regular expression matching correct module names. Overrides module-naming-style. If left empty, module names will be checked with the set naming style.*
**Default:** ``None``
.. _name-group-option:
--name-group
""""""""""""
*Colon-delimited sets of names that determine each other's naming style when the name regexes allow several styles.*
**Default:** ``()``
.. _no-docstring-rgx-option:
--no-docstring-rgx
""""""""""""""""""
*Regular expression which should only match function or class names that do not require a docstring.*
**Default:** ``re.compile('^_')``
.. _paramspec-rgx-option:
--paramspec-rgx
"""""""""""""""
*Regular expression matching correct parameter specification variable names. If left empty, parameter specification variable names will be checked with the set naming style.*
**Default:** ``None``
.. _property-classes-option:
--property-classes
""""""""""""""""""
*List of decorators that produce properties, such as abc.abstractproperty. Add to this list to register other decorators that produce valid properties. These decorators are taken in consideration only for invalid-name.*
**Default:** ``('abc.abstractproperty',)``
.. _typealias-rgx-option:
--typealias-rgx
"""""""""""""""
*Regular expression matching correct type alias names. If left empty, type alias names will be checked with the set naming style.*
**Default:** ``None``
.. _typevar-rgx-option:
--typevar-rgx
"""""""""""""
*Regular expression matching correct type variable names. If left empty, type variable names will be checked with the set naming style.*
**Default:** ``None``
.. _typevartuple-rgx-option:
--typevartuple-rgx
""""""""""""""""""
*Regular expression matching correct type variable tuple names. If left empty, type variable tuple names will be checked with the set naming style.*
**Default:** ``None``
.. _variable-naming-style-option:
--variable-naming-style
"""""""""""""""""""""""
*Naming style matching correct variable names.*
**Default:** ``snake_case``
.. _variable-rgx-option:
--variable-rgx
""""""""""""""
*Regular expression matching correct variable names. Overrides variable-naming-style. If left empty, variable names will be checked with the set naming style.*
**Default:** ``None``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.basic]
# Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any']
argument-naming-style = "snake_case"
# argument-rgx =
# Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any']
attr-naming-style = "snake_case"
# attr-rgx =
bad-names = ["foo", "bar", "baz", "toto", "tutu", "tata"]
bad-names-rgxs = []
# Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any']
class-attribute-naming-style = "any"
# class-attribute-rgx =
# Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any']
class-const-naming-style = "UPPER_CASE"
# class-const-rgx =
# Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any']
class-naming-style = "PascalCase"
# class-rgx =
# Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any']
const-naming-style = "UPPER_CASE"
# const-rgx =
docstring-min-length = -1
# Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any']
function-naming-style = "snake_case"
# function-rgx =
good-names = ["i", "j", "k", "ex", "Run", "_"]
good-names-rgxs = []
include-naming-hint = false
# Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any']
inlinevar-naming-style = "any"
# inlinevar-rgx =
# Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any']
method-naming-style = "snake_case"
# method-rgx =
# Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any']
module-naming-style = "snake_case"
# module-rgx =
name-group = []
no-docstring-rgx = "^_"
# paramspec-rgx =
property-classes = ["abc.abstractproperty"]
# typealias-rgx =
# typevar-rgx =
# typevartuple-rgx =
# Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any']
variable-naming-style = "snake_case"
# variable-rgx =
.. raw:: html
</details>
.. _classes-options:
``Classes`` **Checker**
-----------------------
.. _check-protected-access-in-special-methods-option:
--check-protected-access-in-special-methods
"""""""""""""""""""""""""""""""""""""""""""
*Warn about protected attribute access inside special methods*
**Default:** ``False``
.. _defining-attr-methods-option:
--defining-attr-methods
"""""""""""""""""""""""
*List of method names used to declare (i.e. assign) instance attributes.*
**Default:** ``('__init__', '__new__', 'setUp', 'asyncSetUp', '__post_init__')``
.. _exclude-protected-option:
--exclude-protected
"""""""""""""""""""
*List of member names, which should be excluded from the protected access warning.*
**Default:** ``('_asdict', '_fields', '_replace', '_source', '_make', 'os._exit')``
.. _valid-classmethod-first-arg-option:
--valid-classmethod-first-arg
"""""""""""""""""""""""""""""
*List of valid names for the first argument in a class method.*
**Default:** ``('cls',)``
.. _valid-metaclass-classmethod-first-arg-option:
--valid-metaclass-classmethod-first-arg
"""""""""""""""""""""""""""""""""""""""
*List of valid names for the first argument in a metaclass class method.*
**Default:** ``('mcs',)``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.classes]
check-protected-access-in-special-methods = false
defining-attr-methods = ["__init__", "__new__", "setUp", "asyncSetUp", "__post_init__"]
exclude-protected = ["_asdict", "_fields", "_replace", "_source", "_make", "os._exit"]
valid-classmethod-first-arg = ["cls"]
valid-metaclass-classmethod-first-arg = ["mcs"]
.. raw:: html
</details>
.. _design-options:
``Design`` **Checker**
----------------------
.. _exclude-too-few-public-methods-option:
--exclude-too-few-public-methods
""""""""""""""""""""""""""""""""
*List of regular expressions of class ancestor names to ignore when counting public methods (see R0903)*
**Default:** ``[]``
.. _ignored-parents-option:
--ignored-parents
"""""""""""""""""
*List of qualified class names to ignore when counting class parents (see R0901)*
**Default:** ``()``
.. _max-args-option:
--max-args
""""""""""
*Maximum number of arguments for function / method.*
**Default:** ``5``
.. _max-attributes-option:
--max-attributes
""""""""""""""""
*Maximum number of attributes for a class (see R0902).*
**Default:** ``7``
.. _max-bool-expr-option:
--max-bool-expr
"""""""""""""""
*Maximum number of boolean expressions in an if statement (see R0916).*
**Default:** ``5``
.. _max-branches-option:
--max-branches
""""""""""""""
*Maximum number of branch for function / method body.*
**Default:** ``12``
.. _max-complexity-option:
--max-complexity
""""""""""""""""
*McCabe complexity cyclomatic threshold*
**Default:** ``10``
.. _max-locals-option:
--max-locals
""""""""""""
*Maximum number of locals for function / method body.*
**Default:** ``15``
.. _max-parents-option:
--max-parents
"""""""""""""
*Maximum number of parents for a class (see R0901).*
**Default:** ``7``
.. _max-positional-arguments-option:
--max-positional-arguments
""""""""""""""""""""""""""
*Maximum number of positional arguments for function / method.*
**Default:** ``5``
.. _max-public-methods-option:
--max-public-methods
""""""""""""""""""""
*Maximum number of public methods for a class (see R0904).*
**Default:** ``20``
.. _max-returns-option:
--max-returns
"""""""""""""
*Maximum number of return / yield for function / method body.*
**Default:** ``6``
.. _max-statements-option:
--max-statements
""""""""""""""""
*Maximum number of statements in function / method body.*
**Default:** ``50``
.. _min-public-methods-option:
--min-public-methods
""""""""""""""""""""
*Minimum number of public methods for a class (see R0903).*
**Default:** ``2``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.design]
exclude-too-few-public-methods = []
ignored-parents = []
max-args = 5
max-attributes = 7
max-bool-expr = 5
max-branches = 12
max-complexity = 10
max-locals = 15
max-parents = 7
max-positional-arguments = 5
max-public-methods = 20
max-returns = 6
max-statements = 50
min-public-methods = 2
.. raw:: html
</details>
.. _exceptions-options:
``Exceptions`` **Checker**
--------------------------
.. _overgeneral-exceptions-option:
--overgeneral-exceptions
""""""""""""""""""""""""
*Exceptions that will emit a warning when caught.*
**Default:** ``('builtins.BaseException', 'builtins.Exception')``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.exceptions]
overgeneral-exceptions = ["builtins.BaseException", "builtins.Exception"]
.. raw:: html
</details>
.. _format-options:
``Format`` **Checker**
----------------------
.. _expected-line-ending-format-option:
--expected-line-ending-format
"""""""""""""""""""""""""""""
*Expected format of line ending, e.g. empty (any line ending), LF or CRLF.*
**Default:** ``""``
.. _ignore-long-lines-option:
--ignore-long-lines
"""""""""""""""""""
*Regexp for a line that is allowed to be longer than the limit.*
**Default:** ``^\s*(# )?<?https?://\S+>?$``
.. _ignore-pattern-in-long-lines-option:
--ignore-pattern-in-long-lines
""""""""""""""""""""""""""""""
*Regexp for a part of a line that will not be counted when calculating the line length.*
**Default:** ``None``
.. _indent-after-paren-option:
--indent-after-paren
""""""""""""""""""""
*Number of spaces of indent required inside a hanging or continued line.*
**Default:** ``4``
.. _indent-string-option:
--indent-string
"""""""""""""""
*String used as indentation unit. This is usually "โโโโ" (4 spaces) or "\\t" (1 tab).*
**Default:** ``" "``
.. _max-line-length-option:
--max-line-length
"""""""""""""""""
*Maximum number of characters on a single line. Pylint's default of 100 is based on PEP 8's guidance that teams may choose line lengths up to 99 characters.*
**Default:** ``100``
.. _max-module-lines-option:
--max-module-lines
""""""""""""""""""
*Maximum number of lines in a module.*
**Default:** ``1000``
.. _single-line-class-stmt-option:
--single-line-class-stmt
""""""""""""""""""""""""
*Allow the body of a class to be on the same line as the declaration if body contains single statement.*
**Default:** ``False``
.. _single-line-if-stmt-option:
--single-line-if-stmt
"""""""""""""""""""""
*Allow the body of an if to be on the same line as the test if there is no else.*
**Default:** ``False``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.format]
# Possible choices: ['', 'LF', 'CRLF']
expected-line-ending-format = ""
ignore-long-lines = "^\\s*(# )?<?https?://\\S+>?$"
# ignore-pattern-in-long-lines =
indent-after-paren = 4
indent-string = " "
max-line-length = 100
max-module-lines = 1000
single-line-class-stmt = false
single-line-if-stmt = false
.. raw:: html
</details>
.. _imports-options:
``Imports`` **Checker**
-----------------------
.. _allow-any-import-level-option:
--allow-any-import-level
""""""""""""""""""""""""
*List of modules that can be imported at any level, not just the top level one.*
**Default:** ``()``
.. _allow-reexport-from-package-option:
--allow-reexport-from-package
"""""""""""""""""""""""""""""
*Allow explicit reexports by alias from a package __init__.*
**Default:** ``False``
.. _allow-wildcard-with-all-option:
--allow-wildcard-with-all
"""""""""""""""""""""""""
*Allow wildcard imports from modules that define __all__.*
**Default:** ``False``
.. _deprecated-modules-option:
--deprecated-modules
""""""""""""""""""""
*Deprecated modules which should not be used, separated by a comma.*
**Default:** ``()``
.. _ext-import-graph-option:
--ext-import-graph
""""""""""""""""""
*Output a graph (.gv or any supported image format) of external dependencies to the given file (report RP0402 must not be disabled).*
**Default:** ``""``
.. _import-graph-option:
--import-graph
""""""""""""""
*Output a graph (.gv or any supported image format) of all (i.e. internal and external) dependencies to the given file (report RP0402 must not be disabled).*
**Default:** ``""``
.. _int-import-graph-option:
--int-import-graph
""""""""""""""""""
*Output a graph (.gv or any supported image format) of internal dependencies to the given file (report RP0402 must not be disabled).*
**Default:** ``""``
.. _known-first-party-option:
--known-first-party
"""""""""""""""""""
*Force import order to recognize a module as part of a first party library.*
**Default:** ``()``
.. _known-standard-library-option:
--known-standard-library
""""""""""""""""""""""""
*Force import order to recognize a module as part of the standard compatibility libraries.*
**Default:** ``()``
.. _known-third-party-option:
--known-third-party
"""""""""""""""""""
*Force import order to recognize a module as part of a third party library.*
**Default:** ``('enchant',)``
.. _preferred-modules-option:
--preferred-modules
"""""""""""""""""""
*Couples of modules and preferred modules, separated by a comma.*
**Default:** ``()``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.imports]
allow-any-import-level = []
allow-reexport-from-package = false
allow-wildcard-with-all = false
deprecated-modules = []
ext-import-graph = ""
import-graph = ""
int-import-graph = ""
known-first-party = []
known-standard-library = []
known-third-party = ["enchant"]
preferred-modules = []
.. raw:: html
</details>
.. _logging-options:
``Logging`` **Checker**
-----------------------
.. _logging-format-style-option:
--logging-format-style
""""""""""""""""""""""
*The type of string formatting that logging methods do. `old` means using % formatting, `new` is for `{}` formatting.*
**Default:** ``old``
.. _logging-modules-option:
--logging-modules
"""""""""""""""""
*Logging modules to check that the string format arguments are in logging function parameter format.*
**Default:** ``('logging',)``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.logging]
# Possible choices: ['old', 'new']
logging-format-style = "old"
logging-modules = ["logging"]
.. raw:: html
</details>
.. _method_args-options:
``Method_args`` **Checker**
---------------------------
.. _timeout-methods-option:
--timeout-methods
"""""""""""""""""
*List of qualified names (i.e., library.method) which require a timeout parameter e.g. 'requests.api.get,requests.api.post'*
**Default:** ``('requests.api.delete', 'requests.api.get', 'requests.api.head', 'requests.api.options', 'requests.api.patch', 'requests.api.post', 'requests.api.put', 'requests.api.request')``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.method_args]
timeout-methods = ["requests.api.delete", "requests.api.get", "requests.api.head", "requests.api.options", "requests.api.patch", "requests.api.post", "requests.api.put", "requests.api.request"]
.. raw:: html
</details>
.. _miscellaneous-options:
``Miscellaneous`` **Checker**
-----------------------------
.. _check-fixme-in-docstring-option:
--check-fixme-in-docstring
""""""""""""""""""""""""""
*Whether or not to search for fixme's in docstrings.*
**Default:** ``False``
.. _notes-option:
--notes
"""""""
*List of note tags to take in consideration, separated by a comma.*
**Default:** ``('FIXME', 'XXX', 'TODO')``
.. _notes-rgx-option:
--notes-rgx
"""""""""""
*Regular expression of note tags to take in consideration.*
**Default:** ``""``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.miscellaneous]
check-fixme-in-docstring = false
notes = ["FIXME", "XXX", "TODO"]
notes-rgx = ""
.. raw:: html
</details>
.. _refactoring-options:
``Refactoring`` **Checker**
---------------------------
.. _max-nested-blocks-option:
--max-nested-blocks
"""""""""""""""""""
*Maximum number of nested blocks for function / method body*
**Default:** ``5``
.. _never-returning-functions-option:
--never-returning-functions
"""""""""""""""""""""""""""
*Complete name of functions that never returns. When checking for inconsistent-return-statements if a never returning function is called then it will be considered as an explicit return statement and no message will be printed.*
**Default:** ``('sys.exit', 'argparse.parse_error')``
.. _suggest-join-with-non-empty-separator-option:
--suggest-join-with-non-empty-separator
"""""""""""""""""""""""""""""""""""""""
*Let 'consider-using-join' be raised when the separator to join on would be non-empty (resulting in expected fixes of the type: ``"- " + "
- ".join(items)``)*
**Default:** ``True``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.refactoring]
max-nested-blocks = 5
never-returning-functions = ["sys.exit", "argparse.parse_error"]
suggest-join-with-non-empty-separator = true
.. raw:: html
</details>
.. _similarities-options:
``Similarities`` **Checker**
----------------------------
.. _ignore-comments-option:
--ignore-comments
"""""""""""""""""
*Comments are removed from the similarity computation*
**Default:** ``True``
.. _ignore-docstrings-option:
--ignore-docstrings
"""""""""""""""""""
*Docstrings are removed from the similarity computation*
**Default:** ``True``
.. _ignore-imports-option:
--ignore-imports
""""""""""""""""
*Imports are removed from the similarity computation*
**Default:** ``True``
.. _ignore-signatures-option:
--ignore-signatures
"""""""""""""""""""
*Signatures are removed from the similarity computation*
**Default:** ``True``
.. _min-similarity-lines-option:
--min-similarity-lines
""""""""""""""""""""""
*Minimum lines number of a similarity. Setting it to 0 will disable the check, but you should use disable=duplicate-code instead.*
**Default:** ``4``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.similarities]
ignore-comments = true
ignore-docstrings = true
ignore-imports = true
ignore-signatures = true
min-similarity-lines = 4
.. raw:: html
</details>
.. _spelling-options:
``Spelling`` **Checker**
------------------------
.. _max-spelling-suggestions-option:
--max-spelling-suggestions
""""""""""""""""""""""""""
*Limits count of emitted suggestions for spelling mistakes.*
**Default:** ``4``
.. _spelling-dict-option:
--spelling-dict
"""""""""""""""
*Spelling dictionary name. Available dictionaries depends on your local enchant installation*
**Default:** ``""``
.. _spelling-ignore-comment-directives-option:
--spelling-ignore-comment-directives
""""""""""""""""""""""""""""""""""""
*List of comma separated words that should be considered directives if they appear at the beginning of a comment and should not be checked.*
**Default:** ``fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:``
.. _spelling-ignore-words-option:
--spelling-ignore-words
"""""""""""""""""""""""
*List of comma separated words that should not be checked.*
**Default:** ``""``
.. _spelling-private-dict-file-option:
--spelling-private-dict-file
""""""""""""""""""""""""""""
*A path to a file that contains the private dictionary; one word per line.*
**Default:** ``""``
.. _spelling-store-unknown-words-option:
--spelling-store-unknown-words
""""""""""""""""""""""""""""""
*Tells whether to store unknown words to the private dictionary (see the --spelling-private-dict-file option) instead of raising a message.*
**Default:** ``n``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.spelling]
max-spelling-suggestions = 4
# Possible choices: Values from 'enchant.Broker().list_dicts()' depending on your local enchant installation
spelling-dict = ""
spelling-ignore-comment-directives = "fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:"
spelling-ignore-words = ""
spelling-private-dict-file = ""
spelling-store-unknown-words = false
.. raw:: html
</details>
.. _string-options:
``String`` **Checker**
----------------------
.. _check-quote-consistency-option:
--check-quote-consistency
"""""""""""""""""""""""""
*This flag controls whether inconsistent-quotes generates a warning when the character used as a quote delimiter is used inconsistently within a module.*
**Default:** ``False``
.. _check-str-concat-over-line-jumps-option:
--check-str-concat-over-line-jumps
""""""""""""""""""""""""""""""""""
*This flag controls whether the implicit-str-concat should generate a warning on implicit string concatenation in sequences defined over several lines.*
**Default:** ``False``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.string]
check-quote-consistency = false
check-str-concat-over-line-jumps = false
.. raw:: html
</details>
.. _typecheck-options:
``Typecheck`` **Checker**
-------------------------
.. _contextmanager-decorators-option:
--contextmanager-decorators
"""""""""""""""""""""""""""
*List of decorators that produce context managers, such as contextlib.contextmanager. Add to this list to register other decorators that produce valid context managers.*
**Default:** ``['contextlib.contextmanager']``
.. _generated-members-option:
--generated-members
"""""""""""""""""""
*List of members which are set dynamically and missed by pylint inference system, and so shouldn't trigger E1101 when accessed. Python regular expressions are accepted.*
**Default:** ``()``
.. _ignore-mixin-members-option:
--ignore-mixin-members
""""""""""""""""""""""
*Tells whether missing members accessed in mixin class should be ignored. A class is considered mixin if its name matches the mixin-class-rgx option.*
**Default:** ``True``
.. _ignore-none-option:
--ignore-none
"""""""""""""
*Tells whether to warn about missing members when the owner of the attribute is inferred to be None.*
**Default:** ``True``
.. _ignore-on-opaque-inference-option:
--ignore-on-opaque-inference
""""""""""""""""""""""""""""
*This flag controls whether pylint should warn about no-member and similar checks whenever an opaque object is returned when inferring. The inference can return multiple potential results while evaluating a Python object, but some branches might not be evaluated, which results in partial inference. In that case, it might be useful to still emit no-member and other checks for the rest of the inferred objects.*
**Default:** ``True``
.. _ignored-checks-for-mixins-option:
--ignored-checks-for-mixins
"""""""""""""""""""""""""""
*List of symbolic message names to ignore for Mixin members.*
**Default:** ``['no-member', 'not-async-context-manager', 'not-context-manager', 'attribute-defined-outside-init']``
.. _ignored-classes-option:
--ignored-classes
"""""""""""""""""
*List of class names for which member attributes should not be checked (useful for classes with dynamically set attributes). This supports the use of qualified names.*
**Default:** ``('optparse.Values', 'thread._local', '_thread._local', 'argparse.Namespace')``
.. _known-side-effects-only-functions-option:
--known-side-effects-only-functions
"""""""""""""""""""""""""""""""""""
*Couples of functions with side effects that are often believed to return something and the equivalent function that does return something, separated by a comma. Used to hint at the right function to use in the 'assignment-from-no-return' message.*
**Default:** ``('reverse:reversed', 'sort:sorted')``
.. _missing-member-hint-option:
--missing-member-hint
"""""""""""""""""""""
*Show a hint with possible names when a member name was not found. The aspect of finding the hint is based on edit distance.*
**Default:** ``True``
.. _missing-member-hint-distance-option:
--missing-member-hint-distance
""""""""""""""""""""""""""""""
*The maximum edit distance a name should have in order to be considered a similar match for a missing member name.*
**Default:** ``1``
.. _missing-member-max-choices-option:
--missing-member-max-choices
""""""""""""""""""""""""""""
*The total number of similar names that should be taken in consideration when showing a hint for a missing member.*
**Default:** ``1``
.. _mixin-class-rgx-option:
--mixin-class-rgx
"""""""""""""""""
*Regex pattern to define which classes are considered mixins.*
**Default:** ``.*[Mm]ixin``
.. _signature-mutators-option:
--signature-mutators
""""""""""""""""""""
*List of decorators that change the signature of a decorated function.*
**Default:** ``[]``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.typecheck]
contextmanager-decorators = ["contextlib.contextmanager"]
generated-members = []
ignore-mixin-members = true
ignore-none = true
ignore-on-opaque-inference = true
ignored-checks-for-mixins = ["no-member", "not-async-context-manager", "not-context-manager", "attribute-defined-outside-init"]
ignored-classes = ["optparse.Values", "thread._local", "_thread._local", "argparse.Namespace"]
known-side-effects-only-functions = ["reverse:reversed", "sort:sorted"]
missing-member-hint = true
missing-member-hint-distance = 1
missing-member-max-choices = 1
mixin-class-rgx = ".*[Mm]ixin"
signature-mutators = []
.. raw:: html
</details>
.. _variables-options:
``Variables`` **Checker**
-------------------------
.. _additional-builtins-option:
--additional-builtins
"""""""""""""""""""""
*List of additional names supposed to be defined in builtins. Remember that you should avoid defining new builtins when possible.*
**Default:** ``()``
.. _allow-global-unused-variables-option:
--allow-global-unused-variables
"""""""""""""""""""""""""""""""
*Tells whether unused global variables should be treated as a violation.*
**Default:** ``True``
.. _allowed-redefined-builtins-option:
--allowed-redefined-builtins
""""""""""""""""""""""""""""
*List of names allowed to shadow builtins*
**Default:** ``()``
.. _callbacks-option:
--callbacks
"""""""""""
*List of strings which can identify a callback function by name. A callback name must start or end with one of those strings.*
**Default:** ``('cb_', '_cb')``
.. _dummy-variables-rgx-option:
--dummy-variables-rgx
"""""""""""""""""""""
*A regular expression matching the name of dummy variables (i.e. expected to not be used).*
**Default:** ``_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_``
.. _ignored-argument-names-option:
--ignored-argument-names
""""""""""""""""""""""""
*Argument names that match this expression will be ignored.*
**Default:** ``re.compile('_.*|^ignored_|^unused_')``
.. _init-import-option:
--init-import
"""""""""""""
*Tells whether we should check for unused import in __init__ files.*
**Default:** ``False``
.. _redefining-builtins-modules-option:
--redefining-builtins-modules
"""""""""""""""""""""""""""""
*List of qualified module names which can have objects that can redefine builtins.*
**Default:** ``('six.moves', 'past.builtins', 'future.builtins', 'builtins', 'io')``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.variables]
additional-builtins = []
allow-global-unused-variables = true
allowed-redefined-builtins = []
callbacks = ["cb_", "_cb"]
dummy-variables-rgx = "_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_"
ignored-argument-names = "_.*|^ignored_|^unused_"
init-import = false
redefining-builtins-modules = ["six.moves", "past.builtins", "future.builtins", "builtins", "io"]
.. raw:: html
</details>
Extensions
^^^^^^^^^^
.. _broad_try_clause-options:
``Broad_try_clause`` **Checker**
--------------------------------
.. _max-try-statements-option:
--max-try-statements
""""""""""""""""""""
*Maximum number of statements allowed in a try clause*
**Default:** ``1``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.broad_try_clause]
max-try-statements = 1
.. raw:: html
</details>
.. _code_style-options:
``Code_style`` **Checker**
--------------------------
.. _max-line-length-suggestions-option:
--max-line-length-suggestions
"""""""""""""""""""""""""""""
*Max line length for which to sill emit suggestions. Used to prevent optional suggestions which would get split by a code formatter (e.g., black). Will default to the setting for ``max-line-length``.*
**Default:** ``0``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.code_style]
max-line-length-suggestions = 0
.. raw:: html
</details>
.. _deprecated_builtins-options:
``Deprecated_builtins`` **Checker**
-----------------------------------
.. _bad-functions-option:
--bad-functions
"""""""""""""""
*List of builtins function names that should not be used, separated by a comma*
**Default:** ``['map', 'filter']``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.deprecated_builtins]
bad-functions = ["map", "filter"]
.. raw:: html
</details>
.. _dunder-options:
``Dunder`` **Checker**
----------------------
.. _good-dunder-names-option:
--good-dunder-names
"""""""""""""""""""
*Good dunder names which should always be accepted.*
**Default:** ``[]``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.dunder]
good-dunder-names = []
.. raw:: html
</details>
.. _magic-value-options:
``Magic-value`` **Checker**
---------------------------
.. _valid-magic-values-option:
--valid-magic-values
""""""""""""""""""""
*List of valid magic values that `magic-value-compare` will not detect. Supports integers, floats, negative numbers, for empty string enter ``''``, for backslash values just use one backslash e.g \n.*
**Default:** ``(0, -1, 1, '', '__main__')``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.magic-value]
valid-magic-values = [0, -1, 1, "", "__main__"]
.. raw:: html
</details>
.. _parameter_documentation-options:
``Parameter_documentation`` **Checker**
---------------------------------------
.. _accept-no-param-doc-option:
--accept-no-param-doc
"""""""""""""""""""""
*Whether to accept totally missing parameter documentation in the docstring of a function that has parameters.*
**Default:** ``True``
.. _accept-no-raise-doc-option:
--accept-no-raise-doc
"""""""""""""""""""""
*Whether to accept totally missing raises documentation in the docstring of a function that raises an exception.*
**Default:** ``True``
.. _accept-no-return-doc-option:
--accept-no-return-doc
""""""""""""""""""""""
*Whether to accept totally missing return documentation in the docstring of a function that returns a statement.*
**Default:** ``True``
.. _accept-no-yields-doc-option:
--accept-no-yields-doc
""""""""""""""""""""""
*Whether to accept totally missing yields documentation in the docstring of a generator.*
**Default:** ``True``
.. _default-docstring-type-option:
--default-docstring-type
""""""""""""""""""""""""
*If the docstring type cannot be guessed the specified docstring type will be used.*
**Default:** ``default``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.parameter_documentation]
accept-no-param-doc = true
accept-no-raise-doc = true
accept-no-return-doc = true
accept-no-yields-doc = true
# Possible choices: ['sphinx', 'epytext', 'google', 'numpy', 'default']
default-docstring-type = "default"
.. raw:: html
</details>
.. _typing-options:
``Typing`` **Checker**
----------------------
.. _runtime-typing-option:
--runtime-typing
""""""""""""""""
*Set to ``no`` if the app / library does **NOT** need to support runtime introspection of type annotations. If you use type annotations **exclusively** for type checking of an application, you're probably fine. For libraries, evaluate if some users want to access the type hints at runtime first, e.g., through ``typing.get_type_hints``. Applies to Python versions 3.7 - 3.9*
**Default:** ``True``
.. raw:: html
<details>
<summary><a>Example configuration section</a></summary>
**Note:** Only ``tool.pylint`` is required, the section title is not. These are the default values.
.. code-block:: toml
[tool.pylint.typing]
runtime-typing = true
.. raw:: html
</details>
---
### Doc User Guide Configuration Index (`doc/user_guide/configuration/index.rst`)
.. _all-configurations-options:
=============
Configuration
=============
Pylint is highly configurable. There are a lot of options to follow the needs of
various projects and a lot of checks to activate if they suit your style.
You can generate a sample configuration file with ``--generate-toml-config``
or ``--generate-rcfile``. Every option present on the command line before this
will be included in the file.
For example::
pylint --disable=bare-except,invalid-name --class-rgx='[A-Z][a-z]+' --generate-toml-config
In practice, it is often better to create a minimal configuration file which only contains
configuration overrides. For all other options, Pylint will use its default values.
.. tip::
TOML basic strings use backslashes as escape characters, so each literal
backslash must be doubled. Pylint's generated TOML configuration does this
automatically. When writing regular expression options by hand, single-quoted
`literal strings <https://toml.io/en/v1.0.0#string>`_ avoid the extra escaping.
The ``ignore-paths`` option reserves backslashes as Windows path separators,
so they cannot escape regular expression metacharacters. Use a character class
instead. For example:
.. code-block:: toml
[tool.pylint.main]
ignore-paths = ['^.*[.]pyi$']
.. note::
The internals that create the configuration files fall back to the default values if
no other value was given. This means that some values depend on the interpreter that
was used to generate the file. Most notably ``py-version`` which defaults to the
current interpreter.
.. toctree::
:maxdepth: 2
:titlesonly:
all-options
---
### Doc User Guide Installation Badge (`doc/user_guide/installation/badge.rst`)
.. _badge:
Show your usage
---------------
You can place this badge in your README to let others know your project uses pylint.
.. image:: https://img.shields.io/badge/linting-pylint-yellowgreen
:target: https://github.com/pylint-dev/pylint
Use the badge in your project's README.md (or any other Markdown file)::
[](https://github.com/pylint-dev/pylint)
Use the badge in your project's README.rst (or any other rst file)::
.. image:: https://img.shields.io/badge/linting-pylint-yellowgreen
:target: https://github.com/pylint-dev/pylint
If you use GitHub Actions, and one of your CI workflows begins with "name: pylint", you
can use GitHub's `workflow status badges <https://docs.github.com/en/actions/monitoring-and-troubleshooting-workflows/adding-a-workflow-status-badge#using-the-workflow-file-name>`_
to show an up-to-date indication of whether pushes to your default branch pass pylint.
For more detailed information, check the documentation.
---
### Doc User Guide Installation Command Line Installation (`doc/user_guide/installation/command_line_installation.rst`)
.. _installation:
Command line installation
-------------------------
Pylint is installable using a package manager. Your package manager will find a version that
works with your interpreter. We recommend ``pip``:
.. code-block:: sh
pip install pylint
Or if you want to also check spelling with ``enchant`` (you might need to
`install the enchant C library <https://pyenchant.github.io/pyenchant/install.html#installing-the-enchant-c-library>`_):
.. code-block:: sh
pip install pylint[spelling]
The newest pylint supports all Python interpreters that are not past end of life.
Pylint relies on the ``ast`` module provided by the Python interpreter that runs
it, so that interpreter must be able to parse the syntax used by the code. Newer
interpreters generally provide a more capable parser. However, for projects that
support multiple Python versions, running Pylint on the oldest supported interpreter
is usually the most reliable way to match the compatibility floor. If the lint
environment uses a newer interpreter, set ``py-version`` to the oldest supported
version for version-aware checks; it does not emulate the older interpreter. See
:ref:`using pylint with multiple interpreters <continuous-integration>` for more details.
.. note::
You can also use ``conda`` or your system package manager on debian based OS.
These package managers lag a little behind as they are maintained by a separate
entity on a slower release cycle.
.. code-block:: sh
conda install pylint
.. code-block:: sh
sudo apt-get install pylint
---
### Doc User Guide Installation Index (`doc/user_guide/installation/index.rst`)
Installation
============
Pylint can be installed:
- :ref:`As a command line tool <installation>`
- :ref:`Integrated in your editor/ide <ide-integration>`
- :ref:`As a pre-commit hook <pre-commit-integration>`
- :ref:`With a linter aggregator <linter-aggregators>`
- :ref:`For multiple python interpreters in your continuous integration <continuous-integration>`
.. toctree::
:maxdepth: 2
:titlesonly:
:hidden:
command_line_installation.rst
ide_integration/index
pre-commit-integration.rst
linter-aggregators.rst
with-multiple-interpreters.rst
badge
upgrading_pylint.rst
---
### Doc User Guide Installation Linter Aggregators (`doc/user_guide/installation/linter-aggregators.rst`)
.. _linter-aggregators:
Installation with a linter aggregator
=====================================
Several tools bundle pylint with other linters, so you can get pylint as part of a
larger suite instead of installing and configuring it yourself:
- `Prospector <https://prospector.landscape.io/>`_ runs pylint along with other python
analysis tools and merges everything into a single report.
- `Pylama <https://github.com/klen/pylama>`_ is a code audit tool wrapping pylint and
several other python linters behind one command.
- `MegaLinter <https://megalinter.io/>`_ is a continuous integration oriented aggregator
covering many languages, that `runs pylint out of the box
<https://megalinter.io/latest/descriptors/python_pylint/>`_.
- `Super-Linter <https://github.com/super-linter/super-linter>`_ is a GitHub Action
bundling linters for many languages, pylint included.
Code quality platforms such as `Codacy <https://www.codacy.com/>`_,
`Code Climate <https://codeclimate.com/>`_ and
`SonarQube <https://www.sonarsource.com/products/sonarqube/>`_ can also run pylint or
import its reports.
All those integrations are maintained by third parties: the pylint version they ship
and the options they expose are up to them, so refer to their own documentation.
---
### Doc User Guide Installation Pre Commit Integration (`doc/user_guide/installation/pre-commit-integration.rst`)
.. _pre-commit-integration:
Pre-commit integration
======================
``pylint`` can be used as a `pre-commit <https://pre-commit.com>`_ hook. We however
discourage it as pylint -- due to its speed -- is more suited to a continuous integration
job or a git ``pre-push`` hook, especially if your repository is large.
Since ``pylint`` needs to import modules and dependencies to work correctly, the
hook only works with a local installation of ``pylint`` (in your environment). It means
it can't be used with ``pre-commit.ci``, and you will need to add the following to your
``.pre-commit-config.yaml`` ::
.. sourcecode:: yaml
ci:
skip: [pylint]
Another limitation is that pylint should analyse all your code at once in order to best infer the
actual values that result from calls. If only some of the files are given, pylint might
miss a particular value's type and produce inferior inference for the subset. Since pre-commit slices
the files given to it in order to parallelize the processing, the result can be degraded.
It can also be unexpectedly different when the file set changes because the new slicing can change
the inference. Thus the ``require_serial`` option should be set to ``true`` if correctness and determinism
are more important than parallelization to you.
If you installed ``pylint`` locally it can be added to ``.pre-commit-config.yaml``
as follows. As pylint is slow, a popular option is to run it only before pushing with a
git ``pre-push`` hook instead of on every commit: you can do that with the ``stages``
option, as documented in `pre-commit's guide on confining hooks to run at certain
stages <https://pre-commit.com/#confining-hooks-to-run-at-certain-stages>`_:
.. sourcecode:: yaml
- repo: local
hooks:
- id: pylint
name: pylint
entry: pylint
language: system
types: [python]
stages: [push]
require_serial: true
args:
[
"-rn", # Only display messages
"-sn", # Don't display the score
]
If you want to keep running pylint on every commit, simply omit the ``stages``
option. You can use ``args`` to pass command line arguments as described in the
:ref:`tutorial`. A hook with more arguments could look something like this:
.. sourcecode:: yaml
- repo: local
hooks:
- id: pylint
name: pylint
entry: pylint
language: system
types: [python]
args:
[
"-rn", # Only display messages
"-sn", # Don't display the score
"--rcfile=pylintrc", # Link to your config file
"--load-plugins=pylint.extensions.docparams", # Load an extension
]
---
### Doc User Guide Installation Upgrading Pylint (`doc/user_guide/installation/upgrading_pylint.rst`)
.. _upgrading_pylint:
Upgrading pylint
================
You should probably set the version of pylint in your development environment in order to
choose when you actually upgrade pylint's warnings. pylint is following semver versioning.
But we can't guarantee that the output between version will stays the same. What this means
is that:
.. include:: ../../development_guide/contributor_guide/patch_release.rst
You can expect less messages if you set the minor and upgrade to a new patch version.
But still, if you enable ``useless-suppression`` it still means you can get a new
``useless-suppression`` when a false positive that you disabled is now fixed. Also,
if a library you're using was upgraded and is understood better or worse than the
previous one, you could get new messages too.
.. include:: ../../development_guide/contributor_guide/minor_release.rst
You can expect a lot more change in output, the main one being new checks.
.. include:: ../../development_guide/contributor_guide/major_release.rst
You could have to change the command you're launching or the plugin and
editor integration you're using.
---
### Doc User Guide Installation With Multiple Interpreters (`doc/user_guide/installation/with-multiple-interpreters.rst`)
.. _continuous-integration:
Installation with multiple interpreters
=======================================
Pylint runs inside a real Python interpreter. For most projects, the most reliable
way to check code that supports multiple Python versions is therefore to run Pylint
with the oldest Python version that the project supports. This makes the parser,
standard library, and import environment match the project's compatibility floor.
Sometimes the lint environment intentionally uses a newer interpreter. For example,
a pre-commit configuration might standardize all development tools on Python 3.13
while the project still supports Python 3.11. In that case, set ``py-version`` to
the oldest supported version::
[tool.pylint.main]
py-version = "3.11"
The equivalent command-line option is ``--py-version=3.11``. Without an explicit
value, ``py-version`` defaults to the version of Python that runs Pylint.
``py-version`` tells version-aware checks which Python features are available to
every supported interpreter. For example, it prevents Pylint from suggesting a
refactoring that requires a version newer than Python 3.11 and allows the
unsupported-version checker to report syntax that Python 3.11 cannot use. It does
not switch the interpreter that runs Pylint or emulate that interpreter's complete
standard library and runtime behavior, so running Pylint on the oldest supported
version remains preferable when practical.
Pylint does not guarantee that ``py-version`` will continue to support every
end-of-life Python release indefinitely. If current Pylint cannot analyse the
project's oldest supported release, the best available fallback may be an older
Pylint that still runs on that interpreter, without the fixes and features added
to later Pylint releases.
---
### Doc User Guide Messages Index (`doc/user_guide/messages/index.rst`)
.. _messages:
########
Messages
########
.. toctree::
:maxdepth: 1
:hidden:
messages_overview.rst
message_control.rst
Messages categories
===================
Pylint can emit various messages. These are categorized according
to categories corresponding to bit-encoded exit codes:
* :ref:`Fatal <fatal-category>` (1)
* :ref:`Error <error-category>` (2)
* :ref:`Warning <warning-category>` (4)
* :ref:`Convention <convention-category>` (8)
* :ref:`Refactor <refactor-category>` (16)
* :ref:`Information <information-category>` (NA)
An overview of these messages can be found in :ref:`messages-overview`
Disabling messages
==================
``pylint`` has an advanced message control for its checks, offering the ability
to enable / disable a message either from the command line or from the configuration
file, as well as from the code itself.
For more detail see :ref:`message-control`
---
### Doc User Guide Messages Message Control (`doc/user_guide/messages/message_control.rst`)
.. _message-control:
Messages control
================
In order to control messages, ``pylint`` accepts the following values:
* a symbolic message: ``no-member``, ``undefined-variable`` etc.
* a numerical ID: ``E1101``, ``E1102`` etc.
* The name of the group of checks. You can grab those with ``pylint --list-groups``.
For example, you can disable / enable all the checks related to type checking, with
``typecheck`` or all the checks related to variables with ``variables``
* Corresponding category of the checks
* ``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.
* All the checks with ``all``
.. _block_disables:
Block disables
--------------
This describes how the pragma controls operate at a code level.
The pragma controls can disable / enable:
* All the violations on a single line
.. sourcecode:: python
a, b = ... # pylint: disable=unbalanced-tuple-unpacking
* All the violations on the following line
.. sourcecode:: python
# pylint: disable-next=unbalanced-tuple-unpacking
a, b = ...
* All the violations in a single scope
.. sourcecode:: python
def test():
# Disable all the no-member violations in this function
# pylint: disable=no-member
...
* All the violations in a `block`. For instance, each separate branch of an
``if`` statement is considered a separate block, as in the following example:
.. sourcecode:: python
def meth5(self):
# pylint: disable=no-member
# no error
print(self.bla)
if self.blop:
# pylint: enable=no-member
# enable all no-members for this block
print(self.blip)
else:
# This is affected by the scope disable
print(self.blip)
# pylint: enable=no-member
print(self.blip)
if self.blop:
# pylint: disable=no-member
# disable all no-members for this block
print(self.blip)
else:
# This emits a violation
print(self.blip)
* If the violation occurs on a block starting line, then it applies only to that line
.. sourcecode:: python
if self.blop: # pylint: disable=no-member; applies only to this line
# Here we get an error
print(self.blip)
else:
# error
print(self.blip)
Here's an example with all these rules in a single place:
.. sourcecode:: python
"""pylint option block-disable"""
__revision__ = None
class Foo(object):
"""block-disable test"""
def __init__(self):
pass
def meth1(self, arg):
"""this issues a message"""
print(self)
def meth2(self, arg):
"""and this one not"""
# pylint: disable=unused-argument
print(self\
+ "foo")
def meth3(self):
"""test one line disabling"""
# no error
print(self.bla) # pylint: disable=no-member
# error
print(self.blop)
def meth4(self):
"""test re-enabling"""
# pylint: disable=no-member
# no error
print(self.bla)
print(self.blop)
# pylint: enable=no-member
# error
print(self.blip)
def meth5(self):
"""test IF sub-block re-enabling"""
# pylint: disable=no-member
# no error
print(self.bla)
if self.blop:
# pylint: enable=no-member
# error
print(self.blip)
else:
# no error
print(self.blip)
# no error
print(self.blip)
def meth6(self):
"""test TRY/EXCEPT sub-block re-enabling"""
# pylint: disable=no-member
# no error
print(self.bla)
try:
# pylint: enable=no-member
# error
print(self.blip)
except UndefinedName: # pylint: disable=undefined-variable
# no error
print(self.blip)
# no error
print(self.blip)
def meth7(self):
"""test one line block opening disabling"""
if self.blop: # pylint: disable=no-member
# error
print(self.blip)
else:
# error
print(self.blip)
# error
print(self.blip)
def meth8(self):
"""test late disabling"""
# error
print(self.blip)
# pylint: disable=no-member
# no error
print(self.bla)
print(self.blop)
def meth9(self):
"""test next line disabling"""
# no error
# pylint: disable-next=no-member
print(self.bla)
# error
print(self.blop)
Detecting useless disables
--------------------------
As pylint gets better and false positives are removed,
disables that became useless can accumulate and clutter the code.
In order to clean them you can enable the ``useless-suppression`` warning.
---
### Doc User Guide Messages Messages Overview (`doc/user_guide/messages/messages_overview.rst`)
.. _messages-overview:
#################
Messages overview
#################
.. This file is auto-generated. Make any changes to the associated
.. docs extension in 'doc/exts/pylint_messages.py'.
Pylint can emit the following messages:
Find a message by ID or symbol:
.. raw:: html
<form onsubmit="location='./'+encodeURIComponent(this.message.value);return false">
<label for="message-search">Message ID or symbol</label>
<input id="message-search" name="message" type="search"
placeholder="C0114 or missing-module-docstring" pattern="[A-Za-z0-9-]+" required>
<button type="submit">Open message</button>
</form>
.. _fatal-category:
Fatal
*****
All messages in the fatal category:
.. toctree::
:maxdepth: 2
:titlesonly:
fatal/astroid-error
fatal/config-parse-error
fatal/fatal
fatal/method-check-failed
fatal/parse-error
All renamed messages in the fatal category:
.. toctree::
:maxdepth: 1
:titlesonly:
fatal/old-import-error
.. _error-category:
Error
*****
All messages in the error category:
.. toctree::
:maxdepth: 2
:titlesonly:
error/abstract-class-instantiated
error/access-member-before-definition
error/assigning-non-slot
error/assignment-from-no-return
error/assignment-from-none
error/async-context-manager-with-regular-with
error/await-outside-async
error/bad-configuration-section
error/bad-except-order
error/bad-exception-cause
error/bad-format-character
error/bad-plugin-value
error/bad-reversed-sequence
error/bad-str-strip-call
error/bad-string-format-type
error/bad-super-call
error/bare-name-capture-pattern
error/bidirectional-unicode
error/broken-collections-callable
error/broken-noreturn
error/catching-non-exception
error/class-variable-slots-conflict
error/declare-non-slot
error/dict-iter-missing-items
error/duplicate-argument-name
error/duplicate-bases
error/format-needs-mapping
error/function-redefined
error/import-error
error/inconsistent-mro
error/inherit-non-class
error/init-is-generator
error/invalid-all-format
error/invalid-all-object
error/invalid-bool-returned
error/invalid-bytes-returned
error/invalid-character-backspace
error/invalid-character-carriage-return
error/invalid-character-esc
error/invalid-character-nul
error/invalid-character-sub
error/invalid-character-zero-width-space
error/invalid-class-object
error/invalid-enum-extension
error/invalid-envvar-value
error/invalid-field-call
error/invalid-format-returned
error/invalid-getnewargs-ex-returned
error/invalid-getnewargs-returned
error/invalid-hash-returned
error/invalid-index-returned
error/invalid-lazy-import
error/invalid-length-hint-returned
error/invalid-length-returned
error/invalid-match-args-definition
error/invalid-metaclass
error/invalid-repr-returned
error/invalid-sequence-index
error/invalid-slice-index
error/invalid-slice-step
error/invalid-slots
error/invalid-slots-object
error/invalid-star-assignment-target
error/invalid-str-returned
error/invalid-unary-operand-type
error/invalid-unicode-codec
error/logging-format-truncated
error/logging-too-few-args
error/logging-too-many-args
error/logging-unsupported-format
error/method-hidden
error/misplaced-bare-raise
error/misplaced-format-function
error/missing-format-string-key
error/missing-kwoa
error/mixed-format-string
error/modified-iterating-dict
error/modified-iterating-set
error/multiple-class-sub-patterns
error/no-member
error/no-method-argument
error/no-name-in-module
error/no-self-argument
error/no-value-for-parameter
error/non-iterator-returned
error/nonexistent-operator
error/nonlocal-and-global
error/nonlocal-without-binding
error/not-a-mapping
error/not-an-iterable
error/not-async-context-manager
error/not-callable
error/not-context-manager
error/not-in-loop
error/notimplemented-raised
error/positional-only-arguments-expected
error/possibly-used-before-assignment
error/potential-index-error
error/raising-bad-type
error/raising-non-exception
error/redundant-keyword-arg
error/relative-beyond-top-level
error/repeated-keyword
error/return-arg-in-generator
error/return-in-init
error/return-outside-function
error/singledispatch-method
error/singledispatchmethod-function
error/star-needs-assignment-target
error/syntax-error
error/too-few-format-args
error/too-many-format-args
error/too-many-function-args
error/too-many-positional-sub-patterns
error/too-many-star-expressions
error/truncated-format-string
error/undefined-all-variable
error/undefined-variable
error/unexpected-keyword-arg
error/unexpected-special-method-signature
error/unhashable-member
error/unpacking-non-sequence
error/unrecognized-inline-option
error/unrecognized-option
error/unsubscriptable-object
error/unsupported-assignment-operation
error/unsupported-binary-operation
error/unsupported-delete-operation
error/unsupported-membership-test
error/used-before-assignment
error/used-prior-global-declaration
error/yield-inside-async-function
error/yield-outside-function
All renamed messages in the error category:
.. toctree::
:maxdepth: 1
:titlesonly:
error/bad-context-manager
error/bad-exception-context
error/bad-option-value
error/maybe-no-member
error/old-non-iterator-returned-2
error/old-unbalanced-tuple-unpacking
error/unhashable-dict-key
All permanently deleted messages in the error category:
.. toctree::
:maxdepth: 1
:titlesonly:
error/backtick
error/import-star-module-level
error/old-raise-syntax
error/parameter-unpacking
error/print-statement
error/slots-on-old-class
error/super-on-old-class
error/unpacking-in-except
.. _warning-category:
Warning
*******
All messages in the warning category:
.. toctree::
:maxdepth: 2
:titlesonly:
warning/abstract-method
warning/anomalous-backslash-in-string
warning/anomalous-unicode-escape-in-string
warning/arguments-differ
warning/arguments-out-of-order
warning/arguments-renamed
warning/assert-on-string-literal
warning/assert-on-tuple
warning/attribute-defined-outside-init
warning/bad-builtin
warning/bad-chained-comparison
warning/bad-dunder-name
warning/bad-format-string
warning/bad-format-string-key
warning/bad-indentation
warning/bad-open-mode
warning/bad-staticmethod-argument
warning/bad-thread-instantiation
warning/bare-except
warning/binary-op-exception
warning/boolean-datetime
warning/break-in-finally
warning/broad-exception-caught
warning/broad-exception-raised
warning/cell-var-from-loop
warning/comparison-with-callable
warning/confusing-with-statement
warning/consider-ternary-expression
warning/contextmanager-generator-missing-cleanup
warning/continue-in-finally
warning/dangerous-default-value
warning/deprecated-argument
warning/deprecated-attribute
warning/deprecated-class
warning/deprecated-decorator
warning/deprecated-method
warning/deprecated-module
warning/deprecated-typing-alias
warning/differing-param-doc
warning/differing-type-doc
warning/duplicate-except
warning/duplicate-key
warning/duplicate-string-formatting-argument
warning/duplicate-value
warning/eq-without-hash
warning/eval-used
warning/exec-used
warning/expression-not-assigned
warning/f-string-without-interpolation
warning/fixme
warning/forgotten-debug-statement
warning/format-combined-specification
warning/format-string-without-interpolation
warning/global-at-module-level
warning/global-statement
warning/global-variable-not-assigned
warning/global-variable-undefined
warning/implicit-flag-alias
warning/implicit-str-concat
warning/import-self
warning/inconsistent-quotes
warning/invalid-envvar-default
warning/invalid-format-index
warning/invalid-overridden-method
warning/isinstance-second-argument-not-valid-type
warning/keyword-arg-before-vararg
warning/kwarg-superseded-by-positional-arg
warning/logging-format-interpolation
warning/logging-fstring-interpolation
warning/logging-not-lazy
warning/looping-through-iterator
warning/lost-exception
warning/method-cache-max-size-none
warning/misplaced-future
warning/missing-any-param-doc
warning/missing-format-argument-key
warning/missing-format-attribute
warning/missing-param-doc
warning/missing-parentheses-for-call-in-test
warning/missing-raises-doc
warning/missing-return-doc
warning/missing-return-type-doc
warning/missing-timeout
warning/missing-type-doc
warning/missing-yield-doc
warning/missing-yield-type-doc
warning/modified-iterating-list
warning/multiple-constructor-doc
warning/named-expr-without-context
warning/nan-comparison
warning/nested-min-max
warning/non-ascii-file-name
warning/non-parent-init-called
warning/non-str-assignment-to-dunder-name
warning/overlapping-except
warning/overridden-final-method
warning/pointless-exception-statement
warning/pointless-statement
warning/pointless-string-statement
warning/possibly-unused-variable
warning/preferred-module
warning/protected-access
warning/raise-missing-from
warning/raising-format-tuple
warning/redeclared-assigned-name
warning/redefined-builtin
warning/redefined-loop-name
warning/redefined-outer-name
warning/redefined-slots-in-subclass
warning/redundant-returns-doc
warning/redundant-u-string-prefix
warning/redundant-unittest-assert
warning/redundant-yields-doc
warning/reimported
warning/return-in-finally
warning/self-assigning-variable
warning/self-cls-assignment
warning/shadowed-import
warning/shallow-copy-environ
warning/signature-differs
warning/subclassed-final-class
warning/subprocess-popen-preexec-fn
warning/subprocess-run-check
warning/super-init-not-called
warning/super-without-brackets
warning/too-many-try-statements
warning/try-except-raise
warning/unbalanced-dict-unpacking
warning/unbalanced-tuple-unpacking
warning/undefined-loop-variable
warning/unknown-option-value
warning/unnecessary-ellipsis
warning/unnecessary-lambda
warning/unnecessary-pass
warning/unnecessary-semicolon
warning/unreachable
warning/unspecified-encoding
warning/unused-argument
warning/unused-format-string-argument
warning/unused-format-string-key
warning/unused-import
warning/unused-private-member
warning/unused-variable
warning/unused-wildcard-import
warning/useless-else-on-loop
warning/useless-param-doc
warning/useless-parent-delegation
warning/useless-type-doc
warning/useless-with-lock
warning/using-assignment-expression-in-unsupported-version
warning/using-comprehension-unpacking-in-unsupported-version
warning/using-constant-test
warning/using-exception-groups-in-unsupported-version
warning/using-f-string-in-unsupported-version
warning/using-final-decorator-in-unsupported-version
warning/using-generic-type-syntax-in-unsupported-version
warning/using-lazy-import-in-unsupported-version
warning/using-positional-only-args-in-unsupported-version
warning/while-used
warning/wildcard-import
warning/wrong-exception-operation
All renamed messages in the warning category:
.. toctree::
:maxdepth: 1
:titlesonly:
warning/broad-except
warning/cache-max-size-none
warning/implicit-str-concat-in-sequence
warning/lru-cache-decorating-method
warning/old-assignment-from-none
warning/old-deprecated-argument
warning/old-deprecated-class
warning/old-deprecated-decorator
warning/old-deprecated-method
warning/old-deprecated-module
warning/old-empty-docstring
warning/old-missing-param-doc
warning/old-missing-returns-doc
warning/old-missing-type-doc
warning/old-missing-yields-doc
warning/old-non-iterator-returned-1
warning/old-unidiomatic-typecheck
warning/old-unpacking-non-sequence
warning/useless-super-delegation
All permanently deleted messages in the warning category:
.. toctree::
:maxdepth: 1
:titlesonly:
warning/apply-builtin
warning/assign-to-new-keyword
warning/bad-python3-import
warning/basestring-builtin
warning/buffer-builtin
warning/cmp-builtin
warning/cmp-method
warning/coerce-builtin
warning/coerce-method
warning/comprehension-escape
warning/delslice-method
warning/deprecated-itertools-function
warning/deprecated-lambda
warning/deprecated-operator-function
warning/deprecated-str-translate-call
warning/deprecated-string-function
warning/deprecated-sys-function
warning/deprecated-types-field
warning/deprecated-urllib-function
warning/dict-items-not-iterating
warning/dict-iter-method
warning/dict-keys-not-iterating
warning/dict-values-not-iterating
warning/dict-view-method
warning/div-method
warning/exception-escape
warning/exception-message-attribute
warning/execfile-builtin
warning/file-builtin
warning/filter-builtin-not-iterating
warning/getslice-method
warning/hex-method
warning/idiv-method
warning/implicit-map-evaluation
warning/indexing-exception
warning/input-builtin
warning/intern-builtin
warning/invalid-str-codec
warning/long-builtin
warning/lowercase-l-suffix
warning/map-builtin-not-iterating
warning/metaclass-assignment
warning/mixed-indentation
warning/next-method-called
warning/next-method-defined
warning/no-absolute-import
warning/no-init
warning/nonstandard-exception
warning/nonzero-method
warning/oct-method
warning/old-backtick
warning/old-division
warning/old-indexing-exception
warning/old-old-raise-syntax
warning/old-raising-string
warning/old-unpacking-in-except
warning/property-on-old-class
warning/raising-string
warning/range-builtin-not-iterating
warning/raw_input-builtin
warning/rdiv-method
warning/reduce-builtin
warning/reload-builtin
warning/round-builtin
warning/setslice-method
warning/standarderror-builtin
warning/star-args
warning/sys-max-int
warning/unichr-builtin
warning/unicode-builtin
warning/using-cmp-argument
warning/xrange-builtin
warning/xreadlines-attribute
warning/zip-builtin-not-iterating
.. _convention-category:
Convention
**********
All messages in the convention category:
.. toctree::
:maxdepth: 2
:titlesonly:
convention/bad-classmethod-argument
convention/bad-docstring-quotes
convention/bad-file-encoding
convention/bad-mcs-classmethod-argument
convention/bad-mcs-method-argument
convention/consider-iterating-dictionary
convention/consider-using-any-or-all
convention/consider-using-dict-items
convention/consider-using-enumerate
convention/consider-using-f-string
convention/dict-init-mutate
convention/disallowed-name
convention/docstring-first-line-empty
convention/empty-docstring
convention/import-outside-toplevel
convention/import-private-name
convention/invalid-characters-in-docstring
convention/invalid-name
convention/line-too-long
convention/misplaced-comparison-constant
convention/missing-class-docstring
convention/missing-final-newline
convention/missing-function-docstring
convention/missing-module-docstring
convention/mixed-line-endings
convention/multiple-imports
convention/multiple-statements
convention/non-ascii-module-import
convention/non-ascii-name
convention/single-string-used-for-slots
convention/singleton-comparison
convention/superfluous-parens
convention/too-many-lines
convention/trailing-newlines
convention/trailing-whitespace
convention/typevar-double-variance
convention/typevar-name-incorrect-variance
convention/typevar-name-mismatch
convention/unexpected-line-ending-format
convention/ungrouped-imports
convention/unidiomatic-typecheck
convention/unnecessary-direct-lambda-call
convention/unnecessary-dunder-call
convention/unnecessary-lambda-assignment
convention/unnecessary-negation
convention/use-implicit-booleaness-not-comparison
convention/use-implicit-booleaness-not-comparison-to-string
convention/use-implicit-booleaness-not-comparison-to-zero
convention/use-implicit-booleaness-not-len
convention/use-maxsplit-arg
convention/use-sequence-for-iteration
convention/useless-import-alias
convention/wrong-import-order
convention/wrong-import-position
convention/wrong-spelling-in-comment
convention/wrong-spelling-in-docstring
All renamed messages in the convention category:
.. toctree::
:maxdepth: 1
:titlesonly:
convention/blacklisted-name
convention/compare-to-empty-string
convention/compare-to-zero
convention/len-as-condition
convention/missing-docstring
convention/old-misplaced-comparison-constant
convention/old-non-ascii-name
convention/unneeded-not
All permanently deleted messages in the convention category:
.. toctree::
:maxdepth: 1
:titlesonly:
convention/bad-continuation
convention/bad-whitespace
convention/no-space-after-comma
convention/no-space-after-operator
convention/no-space-before-operator
convention/old-style-class
.. _refactor-category:
Refactor
********
All messages in the refactor category:
.. toctree::
:maxdepth: 2
:titlesonly:
refactor/chained-comparison
refactor/chained-comparison-all-equal
refactor/comparison-of-constants
refactor/comparison-with-itself
refactor/condition-evals-to-constant
refactor/confusing-consecutive-elif
refactor/consider-alternative-union-syntax
refactor/consider-math-not-float
refactor/consider-merging-isinstance
refactor/consider-refactoring-into-while-condition
refactor/consider-swap-variables
refactor/consider-using-alias
refactor/consider-using-assignment-expr
refactor/consider-using-augmented-assign
refactor/consider-using-dict-comprehension
refactor/consider-using-from-import
refactor/consider-using-generator
refactor/consider-using-get
refactor/consider-using-in
refactor/consider-using-join
refactor/consider-using-max-builtin
refactor/consider-using-min-builtin
refactor/consider-using-namedtuple-or-dataclass
refactor/consider-using-set-comprehension
refactor/consider-using-sys-exit
refactor/consider-using-ternary
refactor/consider-using-tuple
refactor/consider-using-with
refactor/cyclic-import
refactor/duplicate-code
refactor/else-if-used
refactor/empty-comment
refactor/impossible-comparison
refactor/inconsistent-return-statements
refactor/literal-comparison
refactor/magic-value-comparison
refactor/match-class-bind-self
refactor/match-class-positional-attributes
refactor/no-classmethod-decorator
refactor/no-else-break
refactor/no-else-continue
refactor/no-else-raise
refactor/no-else-return
refactor/no-self-use
refactor/no-staticmethod-decorator
refactor/prefer-typing-namedtuple
refactor/property-with-parameters
refactor/redefined-argument-from-local
refactor/redefined-variable-type
refactor/redundant-typehint-argument
refactor/simplifiable-condition
refactor/simplifiable-if-expression
refactor/simplifiable-if-statement
refactor/simplify-boolean-expression
refactor/stop-iteration-return
refactor/super-with-arguments
refactor/too-complex
refactor/too-few-public-methods
refactor/too-many-ancestors
refactor/too-many-arguments
refactor/too-many-boolean-expressions
refactor/too-many-branches
refactor/too-many-instance-attributes
refactor/too-many-locals
refactor/too-many-nested-blocks
refactor/too-many-positional-arguments
refactor/too-many-public-methods
refactor/too-many-return-statements
refactor/too-many-statements
refactor/trailing-comma-tuple
refactor/unnecessary-comprehension
refactor/unnecessary-default-type-args
refactor/unnecessary-dict-index-lookup
refactor/unnecessary-list-index-lookup
refactor/use-a-generator
refactor/use-dict-literal
refactor/use-list-literal
refactor/use-set-for-membership
refactor/use-yield-from
refactor/useless-object-inheritance
refactor/useless-option-value
refactor/useless-return
All renamed messages in the refactor category:
.. toctree::
:maxdepth: 1
:titlesonly:
refactor/old-no-self-use
refactor/old-simplifiable-if-statement
refactor/old-too-many-nested-blocks
All permanently deleted messages in the refactor category:
.. toctree::
:maxdepth: 1
:titlesonly:
refactor/abstract-class-little-used
refactor/abstract-class-not-used
.. _information-category:
Information
***********
All messages in the information category:
.. toctree::
:maxdepth: 2
:titlesonly:
information/bad-inline-option
information/c-extension-no-member
information/deprecated-pragma
information/file-ignored
information/locally-disabled
information/raw-checker-failed
information/suppressed-message
information/use-symbolic-message-instead
information/useless-suppression
All renamed messages in the information category:
.. toctree::
:maxdepth: 1
:titlesonly:
information/deprecated-disable-all
---
### Doc User Guide Usage Index (`doc/user_guide/usage/index.rst`)
Usage
=====
.. toctree::
:maxdepth: 2
:titlesonly:
:hidden:
run
output
---
### Doc User Guide Usage Output (`doc/user_guide/usage/output.rst`)
Pylint output
-------------
Output options
''''''''''''''''''''''''''''
Output by default is written to stdout. The simplest way to output to a file is
with the ``--output=<filename>`` option.
The default format for the output is raw text. You can change this by passing
pylint the ``--output-format=<value>`` option. Possible values are:
* ``text``: messages are grouped under a ``************* Module <name>`` header
for each module
* ``no-header``: same as ``text``, without the module headers
* ``parseable``
* ``colorized``: same as ``text``, with ANSI colors
* ``json2``: improved json format
* ``json``: old json format
* ``msvs``: visual studio
* ``github``: `GitHub action messages <https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/workflow-commands-for-github-actions>`_
* ``junit``: JUnit XML for CI/CD integration (Jenkins, Azure DevOps, GitLab CI, GitHub Actions)
You can also give the fully qualified name of your own reporter class, for
example ``--output-format=mypackage.mymodule.MyReporterClass``.
Multiple output formats can be used at the same time by passing
a comma-separated list of formats to ``--output-format``.
This output can be redirected to a file by giving a filename after a colon.
Only one of the formats can write to stdout; the others must be given a file.
For example, to save a json report to ``somefile.json`` and print
a colorized report to stdout at the same time:
::
--output-format=json:somefile.json,colorized
Environment Variables
''''''''''''''''''''''''''''
The colorization of the report written to stdout can also be controlled through
environment variables. Reports written to a file are never changed. The
precedence for determining the output format is as follows:
1. :envvar:`NO_COLOR`
2. :envvar:`FORCE_COLOR`
3. ``--output-format=...``
.. envvar:: NO_COLOR
When set to any non-empty value, a ``colorized`` report on stdout is
replaced by a ``text`` report. This removes every ANSI decoration, not
only the colors: bold, underline and inverse text are gone too.
See https://no-color.org.
.. envvar:: FORCE_COLOR
When set to any non-empty value, a ``text`` report on stdout is replaced
by a ``colorized`` report, with all its decorations, even when stdout is
not a terminal (on Windows too). Other text-based
formats such as ``parseable`` or ``msvs`` are kept as they are.
It is ignored when :envvar:`NO_COLOR` is also set.
See https://force-color.org.
Pylint emits a warning when one of these variables overrides an
``--output-format`` option given on the command line or in the configuration,
or when both are set. Colorizing the default output is silent.
For example, to get a plain report even if ``colorized`` is in your
configuration:
::
NO_COLOR=1 pylint --output-format=colorized my_garden.py
Custom message formats
''''''''''''''''''''''
You can customize the exact way information are displayed using the
`--msg-template=<format string>` option. The `format string` uses the
`Python new format syntax`_ and the following fields are available :
path
relative path to the file
abspath
absolute path to the file
line
line number
column
column number
end_line
line number of the end of the node
end_column
column number of the end of the node
module
module name
obj
object within the module (if any)
msg
text of the message
msg_id
the message code (eg. I0011)
symbol
symbolic name of the message (eg. locally-disabled)
C
one letter indication of the message category
category
fullname of the message category
For example, the former (pre 1.0) default format can be obtained with::
pylint --msg-template='{msg_id}:{line:3d},{column}: {obj}: {msg}'
A few other examples:
* the default format::
{path}:{line}:{column}: {msg_id}: {msg} ({symbol})
* Visual Studio compatible format (former 'msvs' output format)::
{path}({line}): [{msg_id}{obj}] {msg}
* Parseable (Emacs and all, former 'parseable' output format) format::
{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}
The ``--msg-template`` option can only be combined with text-based reporters (``--output-format`` either unspecified or one of: text, no-header, parseable, colorized or msvs).
If both ``--output-format`` and ``--msg-template`` are specified, the ``--msg-template`` option will take precedence over the default line format defined by the reporter class.
If ``end_line`` or ``end_column`` are ``None``, they will be represented as an empty string
by the default ``TextReporter``.
.. _Python new format syntax: https://docs.python.org/2/library/string.html#formatstrings
Source code analysis section
''''''''''''''''''''''''''''
For each python module, Pylint will first display a few '*' characters followed
by the name of the module. Then, a number of messages with the following format:
::
MESSAGE_TYPE: LINE_NUM:[OBJECT:] MESSAGE
You can get another output format, useful since it's recognized by
most editors or other development tools using the ``--output-format=parseable``
option.
The message type can be:
* [I]nformational messages that Pylint emits (do not contribute to your analysis score)
* [R]efactor for a "good practice" metric violation
* [C]onvention for coding standard violation
* [W]arning for stylistic problems, or minor programming issues
* [E]rror for important programming issues (i.e. most probably bug)
* [F]atal for errors which prevented further processing
Sometimes the line of code which caused the error is displayed with
a caret pointing to the error. This may be generalized in future
versions of Pylint.
Example (extracted from a run of Pylint on itself...):
::
************* Module pylint.checkers.format
W: 50: Too long line (86/80)
W:108: Operator not followed by a space
print >>sys.stderr, 'Unable to match %r', line
^
W:141: Too long line (81/80)
W: 74:searchall: Unreachable code
W:171:FormatChecker.process_tokens: Redefining built-in (type)
W:150:FormatChecker.process_tokens: Too many local variables (20/15)
W:150:FormatChecker.process_tokens: Too many branches (13/12)
Reports section
'''''''''''''''
Following the analysis message, Pylint can display a set of reports,
each one focusing on a particular aspect of the project, such as number
of messages by categories, modules dependencies. These features can
be enabled through the ``--reports=y`` option, or its shorthand
version ``-ry``.
For instance, the metrics report displays summaries gathered from the
current run.
* the number of processed modules
* for each module, the percentage of errors and warnings
* the total number of errors and warnings
* percentage of classes, functions and modules with docstrings, and
a comparison from the previous run
* percentage of classes, functions and modules with correct name
(according to the coding standard), and a comparison from the
previous run
* a list of external dependencies found in the code, and where they appear
Score section
'''''''''''''
Finally, Pylint displays a global evaluation score for the code, rated out of a
maximum score of 10.0. This output can be suppressed through the ``--score=n``
option, or its shorthand version ``-sn``.
The evaluation formula can be overridden with the
``--evaluation=<python_expression>`` option.
---
### Doc User Guide Usage Run (`doc/user_guide/usage/run.rst`)
================
Running Pylint
================
On module packages or directories
---------------------------------
Pylint is meant to be called from the command line. The usage is ::
pylint [options] modules_or_packages
By default the ``pylint`` command only accepts a list of python modules and packages.
On versions below 2.15, specifying a directory that is not an explicit package
(with ``__init__.py``) results in an error::
pylint mydir
************* Module mydir
mydir/__init__.py:1:0: F0010: error while code parsing: Unable to load file mydir/__init__.py:
[Errno 2] No such file or directory: 'mydir/__init__.py' (parse-error)
Thus, on versions before 2.15 using the ``--recursive=y`` option allows for linting a namespace package::
pylint --recursive=y mydir mymodule mypackage
This option makes ``pylint`` attempt to discover all modules (files ending with ``.py`` extension)
and all explicit packages (all directories containing a ``__init__.py`` file).
Pylint **will not import** this package or module, but it does use Python internals
to locate them and as such is subject to the same rules and configuration.
You should pay attention to your ``PYTHONPATH``, since it is a common error
to analyze an installed version of a module instead of the development version.
On files
--------
It is also possible to analyze Python files, with a few restrictions. As a convenience,
you can give it a file name if it's possible to guess a module name from the file's
path using the python path. Some examples:
``pylint mymodule.py`` should always work since the current working
directory is automatically added on top of the python path
``pylint directory/mymodule.py`` will work if: ``directory`` is a python
package (i.e. has an ``__init__.py`` file), an implicit namespace package
or if ``directory`` is in the python path.
With implicit namespace packages
--------------------------------
If the analyzed sources use implicit namespace packages (PEP 420), the source root(s) should
be specified using the ``--source-roots`` option. Otherwise, the package names are
detected incorrectly, since implicit namespace packages don't contain an ``__init__.py``.
Globbing support
----------------
It is also possible to specify both directories and files using globbing patterns::
pylint [options] packages/*/src
Command line options
--------------------
.. _run_command_line:
First of all, we have two basic (but useful) options.
--version show program's version number and exit
-h, --help show help about the command line options
Pylint is architected around several checkers. You can disable a specific
checker or some of its messages or message categories by specifying
``--disable=<symbol>``. If you want to enable only some checkers or some
message symbols, first use ``--disable=all`` then
``--enable=<symbol>`` with ``<symbol>`` being a comma-separated list of checker
names and message symbols. See the list of available features for a
description of provided checkers with their functionalities.
The ``--disable`` and ``--enable`` options can be used with comma-separated lists
mixing checkers, message ids and categories like ``-d C,W,no-error,design``
It is possible to disable all messages with ``--disable=all``. This is
useful to enable only a few checkers or a few messages by first
disabling everything, and then re-enabling only what you need.
Each checker has some specific options, which can take either a yes/no
value, an integer, a python regular expression, or a comma-separated
list of values (which are generally used to override a regular
expression in special cases). For a full list of options, use ``--help``
Specifying all the options suitable for your setup and coding
standards can be tedious, so it is possible to use a configuration file to
specify the default values. You can specify a configuration file on the
command line using the ``--rcfile`` option. Otherwise, Pylint searches for a
configuration file in the following order and uses the first one it finds:
#. ``pylintrc`` in the current working directory
#. ``pylintrc.toml`` in the current working directory,
providing it has at least one ``tool.pylint.`` section.
#. ``.pylintrc`` in the current working directory
#. ``.pylintrc.toml`` in the current working directory,
providing it has at least one ``tool.pylint.`` section.
#. ``pyproject.toml`` in the current working directory,
providing it has at least one ``tool.pylint.`` section.
The ``pyproject.toml`` must prepend section names with ``tool.pylint.``,
for example ``[tool.pylint.'MESSAGES CONTROL']``. They can also be passed
in on the command line.
#. ``setup.cfg`` in the current working directory,
providing it has at least one ``pylint.`` section
#. ``tox.ini`` in the current working directory,
providing it has at least one ``pylint.`` section
#. Pylint will search for the ``pyproject.toml`` file up the directories hierarchy
unless it's found, or a ``.git``/``.hg`` directory is found, or the file system root
is approached.
#. If the current working directory is in a Python package, Pylint searches \
up the hierarchy of Python packages until it finds a ``pylintrc`` file. \
This allows you to specify coding standards on a module-by-module \
basis. Of course, a directory is judged to be a Python package if it \
contains an ``__init__.py`` file.
#. The file named by environment variable ``PYLINTRC``
#. if you have a home directory which isn't ``/root``:
#. ``.pylintrc`` in your home directory
#. ``.config/pylintrc`` in your home directory
#. ``/etc/pylintrc``
The ``--generate-toml-config`` option will generate a commented configuration file
on standard output according to the current configuration and exit. This
includes:
* Any configuration file found as explained above
* Options appearing before ``--generate-toml-config`` on the Pylint command line
Of course you can also start with the default values and hand-tune the
configuration.
Other useful global options include:
--ignore=<file[,file...]> Files or directories to be skipped. They should be
base names, not paths.
--output-format=<format> Select output format (text, json, custom).
--msg-template=<template> Modify text output message template.
--list-msgs Generate pylint's messages.
--list-msgs-enabled Display a list of what messages are enabled and
disabled with the given configuration.
--full-documentation Generate pylint's full documentation, in reST
format.
Parallel execution
------------------
It is possible to speed up the execution of Pylint. If the running computer
has more CPUs than one, then the work for checking all files could be spread across all
cores via Pylints's sub-processes.
This functionality is exposed via the ``-j`` command-line parameter.
If the provided number is 0, then the total number of CPUs will be autodetected and used.
Example::
pylint -j 4 mymodule1.py mymodule2.py mymodule3.py mymodule4.py
This will spawn 4 parallel Pylint sub-process, where each provided module will
be checked in parallel. Discovered problems by checkers are not displayed
immediately. They are shown just after checking a module is complete.
You can also do your own parallelization by launching pylint multiple times on subsets
of your files (like ``pre-commit`` with the default ``require_serial=false`` does).
Be aware, though: pylint should analyse all your code at once in order to best infer
the actual values that result from calls. If only some of the files are given, pylint
might miss a particular value's type and produce inferior inference for the subset.
It can also be unexpectedly different when the file set changes because the new
slicing can change the inference. So, don't do this if correctness and determinism
are important to you.
Exit codes
----------
Pylint returns bit-encoded exit codes.
========= =========================
exit code meaning
========= =========================
0 no error
1 fatal message issued
2 error message issued
4 warning message issued
8 refactor message issued
16 convention message issued
32 usage error
========= =========================
For example, an exit code of ``20`` means there was at least one warning message (4)
and at least one convention message (16) and nothing else.
---
### Doc Whatsnew 0 0.X (`doc/whatsnew/0/0.x.rst`)
What's New in Pylint 0.28.0?
============================
Release date: 2013-04-25
* bitbucket #1: fix "dictionary changed size during iteration" crash
* #74013: new E1310[bad-str-strip-call] message warning when a call to a
{l,r,}strip method contains duplicate characters (patch by Torsten Marek)
* #123233: new E0108[duplicate-argument-name] message reporting duplicate
argument names
* #81378: emit W0120[useless-else-on-loop] for loops without break
* #124660: internal dependencies should not appear in external dependencies
report
* #124662: fix name error causing crash when symbols are included in output
messages
* #123285: apply pragmas for warnings attached to lines to physical source
code lines
* #123259: do not emit E0105 for yield expressions inside lambdas
* #123892: don't crash when attempting to show source code line that can't
be encoded with the current locale settings
* Simplify checks for dangerous default values by unifying tests for all
different mutable compound literals.
* Improve the description for :ref:`redundant-keyword-arg`
What's New in Pylint 0.27.0?
============================
Release date: 2013-02-26
* #20693: replace pylint.el by Ian Eure version (patch by J.Kotta)
* #105327: add support for --disable=all option and deprecate the
'disable-all' inline directive in favour of 'skip-file' (patch by
A.Fayolle)
* #110840: add messages I0020 and I0021 for reporting of suppressed
messages and useless suppression pragmas. (patch by Torsten Marek)
* #112728: add warning E0604 for non-string objects in __all__
(patch by Torsten Marek)
* #120657: add warning W0110/deprecated-lambda when a map/filter
of a lambda could be a comprehension (patch by Martin Pool)
* #113231: logging checker now looks at instances of Logger classes
in addition to the base logging module. (patch by Mike Bryant)
* #111799: don't warn about octal escape sequence, but warn about ``\o``
which is not octal in Python (patch by Martin Pool)
* #110839: bind <F5> to Run button in pylint-gui
* #115580: fix erroneous W0212 (access to protected member) on super call
(patch by Martin Pool)
* #110853: fix a crash when an __init__ method in a base class has been
created by assignment rather than direct function definition (patch by
Torsten Marek)
* #110838: fix pylint-gui crash when include-ids is activated (patch by
Omega Weapon)
* #112667: fix emission of reimport warnings for mixed imports and extend
the testcase (patch by Torsten Marek)
* #112698: fix crash related to non-inferable __all__ attributes and
invalid __all__ contents (patch by Torsten Marek)
* Python 3 related fixes:
* #110213: fix import of checkers broken with python 3.3, causing
"No such message id W0704" breakage
* #120635: redefine cmp function used in pylint.reporters
* Include full warning id for I0020 and I0021 and make sure to flush
warnings after each module, not at the end of the pylint run.
(patch by Torsten Marek)
* Changed the regular expression for inline options so that it must be
preceded by a # (patch by Torsten Marek)
* Make dot output for import graph predictable and not depend
on ordering of strings in hashes. (patch by Torsten Marek)
* Add hooks for import path setup and move pylint's sys.path
modifications into them. (patch by Torsten Marek)
What's New in Pylint 0.26.0?
============================
Release date: 2012-10-05
* #106534: add --ignore-imports option to code similarity checking
and 'symilar' command line tool (patch by Ry4an Brase)
* #104571: check for anomalous backslash escape, introducing new
W1401 and W1402 messages (patch by Martin Pool)
* #100707: check for boolop being used as exception class, introducing
new W0711 message (patch by Tim Hatch)
* #4014: improve checking of metaclass methods first args, introducing
new C0204 message (patch by [email protected] finalized by sthenault)
* #4685: check for consistency of a module's __all__ variable,
introducing new E0603 message
* #105337: allow custom reporter in output-format (patch by Kevin Jing Qiu)
* #104420: check for protocol completeness and avoid false R0903
(patch by Peter Hammond)
* #100654: fix grammatical error for W0332 message (using 'l' as
long int identifier)
* #103656: fix W0231 false positive for missing call to object.__init__
(patch by [email protected])
* #63424: fix similarity report disabling by properly renaming it to RP0801
* #103949: create a console_scripts entry point to be used by
easy_install, buildout and pip
* fix cross-interpreter issue (non compatible access to __builtins__)
* stop including tests files in distribution, they causes crash when
installed with python3 (#72022, #82417, #76910)
What's New in Pylint 0.25.2?
============================
Release date: 2012-07-17
* #93591: Correctly emit warnings about clobbered variable names when an
except handler contains a tuple of names instead of a single name.
(patch by [email protected])
* #7394: W0212 (access to protected member) not emitted on assignments
(patch by [email protected])
* #18772; no prototype consistency check for mangled methods (patch by
[email protected])
* #92911: emit W0102 when sets are used as default arguments in functions
(patch by [email protected])
* #77982: do not emit E0602 for loop variables of comprehensions
used as argument values inside a decorator (patch by [email protected])
* #89092: don't emit E0202 (attribute hiding a method) on @property methods
* #92584: fix pylint-gui crash due to internal API change
* #87192: fix crash when decorators are accessed through more than one dot
(for instance @a.b is fine, @a.b.c crash)
* #88914: fix parsing of --generated-members options, leading to crash
when using a regexp value set
* fix potential crashes with utils.safe_infer raising InferenceError
What's New in Pylint 0.25.1?
============================
Release date: 2011-12-08
* #81078: Warn if names in exception handlers clobber overwrite
existing names (patch by [email protected])
* #81113: Fix W0702 messages appearing with the wrong line number.
(patch by [email protected])
* #50461, #52020, #51222: Do not issue warnings when using 2.6's
property.setter/deleter functionality (patch by [email protected])
* #9188, #4024: Do not trigger W0631 if a loop variable is assigned
in the else branch of a for loop.
What's New in Pylint 0.25.0?
============================
Release date: 2011-10-7
* #74742: make allowed name for first argument of class method configurable
(patch by Google)
* #74087: handle case where inference of a module return YES; this avoid
some cases of "TypeError: '_Yes' object does not support indexing" (patch
by Google)
* #74745: make "too general" exception names configurable (patch by Google)
* #74747: crash occurs when lookup up a special attribute in class scope
(patch by google)
* #76920: crash if on e.g. "pylint --rcfile" (patch by Torsten Marek)
* #77237: warning for E0202 may be very misleading
* #73941: HTML report messages table is badly rendered
What's New in Pylint 0.24.0?
============================
Release date: 2011-07-18
* #69738: add regular expressions support for "generated-members"
* ids of logging and string_format checkers have been changed:
logging: 65 -> 12, string_format: 99 -> 13
Also add documentation to say that ids of range 1-50 shall be reserved
to pylint internal checkers
* #69993: Additional string format checks for logging module:
check for missing arguments, too many arguments, or invalid string
formats in the logging checker module. Contributed by Daniel Arena
* #69220: add column offset to the reports. If you've a custom reporter,
this change may break it has now location gain a new item giving the
column offset.
* #60828: Fix false positive in reimport check
* #70495: absolute imports fail depending on module path (patch by Jacek Konieczny)
* #22273: Fix --ignore option documentation to match reality
What's New in Pylint 0.23.0?
============================
Release date: 2011-01-11
* documentation update, add manpages
* several performance improvements
* finalize python3 support
* new W0106 warning 'Expression "%s" is assigned to nothing'
* drop E0501 and E0502 messages about wrong source encoding: not anymore
interesting since it's a syntax error for python >= 2.5 and we now only
support this python version and above.
* don't emit W0221 or W0222 when methods as variable arguments (e.g. \*arg
and/or \*\*args). Patch submitted by Charles Duffy.
What's New in Pylint 0.22.0?
============================
Release date: 2010-11-15
* python versions: minimal python3.x support; drop python < 2.5 support
What's New in Pylint 0.21.4?
============================
Release date: 2010-10-27
* fix #48066: pylint crashes when redirecting output containing non-ascii characters
* fix #19799: "pylint -blah" exit with status 2
* update documentation
What's New in Pylint 0.21.3?
============================
Release date: 2010-09-28
* restored python 2.3 compatibility. Along with logilab-astng
0.21.3 and logilab-common 0.52, this will much probably be the
latest release supporting python < 2.5.
What's New in Pylint 0.21.2?
============================
Release date: 2010-08-26
* fix #36193: import checker raise exception on cyclic import
* fix #28796: regression in --generated-members introduced pylint 0.20
* some documentation cleanups
What's New in Pylint 0.21.1?
============================
Release date: 2010-06-04
* fix #28962: pylint crash with new options, due to missing stats data while
writing the Statistics by types report
* updated man page to 0.21 or greater command line usage (fix debian #582494)
What's New in Pylint 0.21.0?
============================
Release date: 2010-05-11
* command line updated (closes #9774, #9787, #9992, #22962):
* all enable-* / disable-* options have been merged into --enable / --disable
* BACKWARD INCOMPATIBLE CHANGE: short name of --errors-only becomes -E, -e being
affected to --enable
* pylint --help output much simplified, with --long-help available to get the
complete one
* revisited gui, thanks to students from Toronto university (they are great
contributors to this release!)
* fix #21591: html reporter produces no output if reports is set to 'no'
* fix #4581: not Missing docstring (C0111) warning if a method is overridden
* fix #4683: Non-ASCII characters count double if utf8 encode
* fix #9018: when using defining-attr-method, method order matters
* fix #4595: Comma not followed by a space should not occurs on trailing comma
in list/tuple/dict definition
* fix #22585: [Patch] fix man warnings for pyreverse.1 manpage
* fix #20067: AttributeError: 'NoneType' object has no attribute 'name' with with
What's New in Pylint 0.20.0?
============================
Release date: 2010-03-01
* fix #19498: fix windows batch file
* fix #19339: pylint.el : non existing py-mod-map
(closes Debian Bug report logs - #475939)
* implement #18860, new W0199 message on assert (a, b)
* implement #9776, 'W0150' break or return statement in finally block may
swallow exception.
* fix #9263, __init__ and __new__ are checked for unused arguments
* fix #20991, class scope definitions ignored in a genexpr
* fix #5975, Abstract intermediate class not recognized as such
* fix #5977, yield and return statement have their own counters, no more R0911
(Too many return statements) when a function have many yield stamtements
* implement #5564, function / method arguments with leading "_" are ignored in
arguments / local variables count.
* implement #9982, E0711 specific error message when raising NotImplemented
* remove --cache-size option
What's New in Pylint 0.19.0?
============================
Release date: 2009-12-18
* implement #18947, #5561: checker for function arguments
* include James Lingard string format checker
* include simple message (ids) listing by Vincent Ferotin (#9791)
* --errors-only does not hide fatal error anymore
* include james Lingard patches for ++/-- and duplicate key in dicts
* include James Lingard patches for function call arguments checker
* improved Flymake code and doc provided by Derek Harland
* refactor and fix the imports checker
* fix #18862: E0601 false positive with lambda functions
* fix #8764: More than one statement on a single line false positive with
try/except/finally
* fix #9215: false undefined variable error in lambda function
* fix for w0108 false positive (Nathaniel)
* fix test/fulltest.sh
* #5821 added a utility function to run pylint in another process (patch provide by Vincent Ferotin)
What's New in Pylint 0.18.0?
============================
Release date: 2009-03-25
* tests ok with python 2.4, 2.5, 2.6. 2.3 not tested
* fix #8687, W0613 false positive on inner function
* fix #8350, C0322 false positive on multi-line string
* fix #8332: set E0501 line no to the first line where non ascii character
has been found
* avoid some E0203 / E0602 false negatives by detecting respectively
AttributeError / NameError
* implements #4037: don't issue W0142 (* or ** magic) when they are barely
passed from */** arguments
* complete #5573: more complete list of special methods, also skip W0613
for python internal method
* don't show information messages by default
* integration of Yuen Ho Wong's patches on Emacs lisp files
What's New in Pylint 0.17.0?
============================
Release date: 2009-03-19
* semicolon check : move W0601 to W0301
* remove rpython : remove all rpython checker, modules and tests
* astng 0.18 compatibility: support for _ast module modifies interfaces
What's New in Pylint 0.16.0?
============================
Release date: 2009-01-28
* change [en|dis]able-msg-cat options: only accept message categories
identified by their first letter (e.g. IRCWEF) without the need for comma
as separator
* add epylint.bat script to fix Windows installation
* setuptools/easy_install support
* include a modified version of Maarten ter Huurne patch to avoid W0613
warning on arguments from overridden method
* implement #5575 drop dumb W0704 message) by adding W0704 to ignored
messages by default
* new W0108 message, checking for suspicious lambda (provided by Nathaniel
Manista)
* fix W0631, false positive reported by Paul Hachmann
* fix #6951: false positive with W0104
* fix #6949
* patches by Mads Kiilerich:
* implement #4691, make pylint exits with a non zero return
status if any messages other then Information are issued
* fix #3711, #5626 (name resolution bug w/ decorator and class members)
* fix #6954
What's New in Pylint 0.15.2?
============================
Release date: 2008-10-13
* fix #5672: W0706 weirdness ( W0706 removed )
* fix #5998: documentation points to wrong url for mailing list
* fix #6022: no error message on wrong module names
* fix #6040: pytest doesn't run test/func_test.py
What's New in Pylint 0.15.1?
============================
Release date: 2008-09-15
* fix #4910: default values are missing in manpage
* fix #5991: missing files in 0.15.0 tarball
* fix #5993: epylint should work with python 2.3
What's New in Pylint 0.15.0?
============================
Release date: 2008-09-10
* include pyreverse package and class diagram generation
* included Stefan Rank's patch to deal with 2.4 relative import
* included Robert Kirkpatrick's tutorial and typos fixes
* fix bug in reenabling message
* fix #2473: invoking pylint on __init__.py (hopefully)
* typecheck: acquired-members option has been dropped in favor of the more
generic generated-members option. If the zope option is set, the behaviour
is now to add some default values to generated-members.
* Flymake integration: added bin/epylint and elisp/pylint-flymake.el
What's New in Pylint 0.14.0?
============================
Release date: 2008-01-14
* fix #3733: Messages (dis)appear depending on order of file names
* fix #4026: pylint.el should require compile
* fix a bug in colorized reporter, spotted by Dave Borowitz
* applied patch from Stefan Rank to avoid W0410 false positive when
multiple "from __future__" import statements
* implement #4012: flag back tick as deprecated (new W0333 message)
* new ignored-class option on typecheck checker allowing to skip members
checking based on class name (patch provided by Thomas W Barr)
What's New in Pylint 0.13.2?
============================
Release date: 2007-06-07
* fix disable-checker option so that it won't accidentally enable the
rpython checker which is disabled by default
* added note about the gedit plugin into documentation
What's New in Pylint 0.13.1?
============================
Release date: 2007-03-02
* fix some unexplained 0.13.0 packaging issue which led to a bunch of
files missing from the distribution
What's New in Pylint 0.13.0?
============================
Release date: 2007-02-28
* new RPython (Restricted Python) checker for PyPy fellow or people
wanting to get a compiled version of their python program using the
translator of the PyPy project. For more information about PyPy or
RPython, visit https://www.pypy.org, previously codespeak.net/pypy/
* new E0104 and E0105 messages introduced to respectively warn about
"return" and "yield" outside function or method
* new E0106 message when "yield" and "return something" are mixed in a
function or method
* new W0107 message for unnecessary pass statement
* new W0614 message to differentiate between unused ``import X`` and
unused `from X import *` (#3209, patch submitted by Daniel Drake)
* included Daniel Drake's patch to have a different message E1003 instead of
E1001 when a missing member is found but an inference failure has been
detected
* msvs reporter for Visual Studio line number reporting (#3285)
* allow disable-all option inline (#3218, patch submitted by Daniel Drake)
* --init-hook option to call arbitrary code necessary to set
environment (e.g. sys.path) (#3156)
* One more Daniel's patch fixing a command line option parsing
problem, this'll definitely be the DDrake release :)
* fix #3184: crashes on "return" outside function
* fix #3205: W0704 false positive
* fix #3123: W0212 false positive on static method
* fix #2485: W0222 false positive
* fix #3259: when a message is explicitly enabled, check the checker
emitting it is enabled
What's New in Pylint 0.12.2?
============================
Release date: 2006-11-23
* fix #3143: W0233 bug w/ YES objects
* fix #3119: Off-by-one error counting lines in a file
* fix #3117: ease sys.stdout overriding for reporters
* fix #2508: E0601 false positive with lambda
* fix #3125: E1101 false positive and a message duplication. Only the last part
is actually fixed since the initial false positive is due to dynamic setting of
attributes on the decimal.Context class.
* fix #3149: E0101 false positives and introduced E0100 for generator __init__
methods
* fixed some format checker false positives
What's New in Pylint 0.12.1?
============================
Release date: 2006-09-25
* fixed python >= 2.4 format false positive with multiple lines statement
* fixed some 2.5 issues
* fixed generator expression scope bug (depends on astng 0.16.1)
* stop requiring __revision__
What's New in Pylint 0.12.0?
============================
Release date: 2006-08-10
* usability changes:
* parseable, html and color options are now handled by a single
output-format option
* enable-<checkerid> and disable-all options are now handled by
two (exclusive) enable-checker and disable-checker options
taking a comma separated list of checker names as value
* renamed debug-mode option to errors-only
* started a reference user manual
* new W0212 message for access to protected member from client code
(Closes #14081)
* new W0105 and W0106 messages extracted from W0104 (statement seems
to have no effect) respectively when the statement is actually string
(that's sometimes used instead of comments for documentation) or an
empty statement generated by a useless semicolon
* reclassified W0302 to C0302
* fix so that global messages are not anymore connected to the last
analyzed module (Closes #10106)
* fix some bugs related to local disabling of messages
* fix cr/lf pb when generating the rc file on windows platforms
What's New in Pylint 0.11.0?
============================
Release date: 2006-04-19
* fix crash caused by the exceptions checker in some case
* fix some E1101 false positive with abstract method or classes defining
__getattr__
* dirty fix to avoid "_socketobject" has not "connect" member. The actual
problem is that astng isn't able to understand the code used to create
socket.socket object with exec
* added an option in the similarity checker to ignore docstrings, enabled
by default
* included patch from Benjamin Niemann to allow block level
enabling/disabling of messages
What's New in Pylint 0.10.0?
============================
Release date: 2006-03-06
* WARNING, this release include some configuration changes (see below),
so you may have to check and update your own configuration file(s) if
you use one
* this release require the 0.15 version of astng or superior (it will save
you a lot of pylint crashes...)
* W0705 has been reclassified to E0701, and is now detecting more
inheriting problem, and a false positive when empty except clause is
following an Exception catch has been fixed (Closes #10422)
* E0212 and E0214 (metaclass/class method should have mcs/cls as first
argument have been reclassified to C0202 and C0203 since this not as
well established as "self" for instance method (E0213)
* W0224 has been reclassified into F0220 (failed to resolve interfaces
implemented by a class)
* a new typecheck checker, introducing the following checks:
- E1101, access to nonexistent member (implements #10430), remove
the need of E0201 and so some options has been moved from the
classes checker to this one
- E1102, calling a non callable object
- E1111 and W1111 when an assignment is done on a function call but the
inferred function returns None (implements #10431)
* change in the base checker:
- checks module level and instance attribute names (new const-rgx
and attr-rgx configuration option) (implements #10209 and
#10440)
- list comprehension and generator expression variables have their
own regular expression (the inlinevar-rgx option) (implements
#9146)
- the C0101 check with its min-name-length option has
been removed (this can be specified in the regxp after all...)
- W0103 and W0121 are now handled by the variables checker
(W0103 is now W0603 and W0604 has been split into different messages)
- W0131 and W0132 messages have been reclassified to C0111 and
C0112 respectively
- new W0104 message on statement without effect
* regexp support for dummy-variables (dummy-variables-rgx option
replace dummy-variables) (implements #10027)
* better global statement handling, see W0602, W0603, W0604 messages
(implements #10344 and #10236)
* --debug-mode option, disabling all checkers without error message
and filtering others to only display error
* fixed some R0201 (method could be a function) false positive
What's New in Pylint 0.9.0?
============================
Release date: 2006-01-10
* a lot of updates to follow astng 0.14 API changes, so install
logilab-astng 0.14 or greater before using this version of pylint
* checker number 10 ! newstyle will search for problems regarding old
style / new style classes usage problems (rely on astng 0.14 new
style detection feature)
* new 'load-plugins' options to load additional pylint plugins (usable
from the command line or from a configuration file) (implements
#10031)
* check if a "pylintrc" file exists in the current working directory
before using the one specified in the PYLINTRC environment variable
or the default ~/.pylintrc or /etc/pylintrc
* fixed W0706 (Identifier used to raise an exception is assigned...)
false positive and reraising a caught exception instance
* fixed E0611 (No name get in module blabla) false positive when accessing
to a class'__dict__
* fixed some E0203 ("access to member before its definition") false
positive
* fixed E0214 ("metaclass method first argument should be mcs) false
positive with staticmethod used on a metaclass
* fixed packaging which was missing the test/regrtest_data directory
* W0212 (method could be a function) has been reclassified in the
REFACTOR category as R0201, and is no more considerer when a method
overrides an abstract method from an ancestor class
* include module name in W0401 (wildcard import), as suggested by
Amaury
* when using the '--parseable', path are written relative to the
current working directory if in a sub-directory of it (#9789)
* 'pylint --version' shows logilab-astng and logilab-common versions
* fixed pylint.el to handle space in file names
* misc lint style fixes
What's New in Pylint 0.8.1?
============================
Release date: 2005-11-07
* fix "deprecated module" false positive when the code imports a
module whose name starts with a deprecated module's name (close
#10061)
* fix "module has no name __dict__" false positive (Closes #10039)
* fix "access to undefined variable __path__" false positive (close
#10065)
* fix "explicit return in __init__" false positive when return is
actually in an inner function (Closes #10075)
What's New in Pylint 0.8.0?
============================
Release date: 2005-10-21
* check names imported from a module exists in the module (E0611),
patch contributed by Amaury Forgeot d'Arc
* print a warning (W0212) for methods that could be a function
(implements #9100)
* new --defining-attr-methods option on classes checker
* new --acquired-members option on the classes checker, used when
--zope=yes to avoid false positive on acquired attributes (listed
using this new option) (Closes #8616)
* generate one E0602 for each use of an undefined variable
(previously, only one for the first use but not for the following)
(implements #1000)
* make profile option saveable
* fix Windows .bat file, patch contributed by Amaury Forgeot d'Arc
* fix one more false positive for E0601 (access before definition)
with for loop such as "for i in range(10): print i" (test
func_noerror_defined_and_used_on_same_line)
* fix false positive for E0201 (undefined member) when accessing to
__name__ on a class object
* fix astng checkers traversal order
* fix bug in format checker when parsing a file from a platform
using different new line characters (Closes #9239)
* fix encoding detection regexp
* fix --rcfile handling (support for --rcfile=file, Closes #9590)
What's New in Pylint 0.7.0?
============================
Release date: 2005-05-27
* WARNING: pylint is no longer a logilab subpackage. Users may have to
manually remove the old logilab/pylint directory.
* introduce a new --additional-builtins option to handle user defined
builtins
* --reports option has now -r as short alias, and -i for --include-ids
* fix a bug in the variables checker which may causing some false
positives when variables are defined and used within the same
statement (test func_noerror_defined_and_used_on_same_line)
* this time, real fix of the "disable-msg in the config file" problem,
test added to unittest_lint
* fix bug with --list-messages and python -OO
* fix possible false positive for W0201
What's New in Pylint 0.6.4?
===========================
Release date: 2005-04-14
* allow to parse files without extension when a path is given on the
command line (test noext)
* don't fail if we are unable to read an inline option (e.g. inside a
module), just produce an information message (test func_i0010)
* new message E0103 for break or continue outside loop (Closes #8883,
test func_continue_not_in_loop)
* fix bug in the variables checker, causing non detection of some
actual name error (Closes #8884, test
func_nameerror_on_string_substitution)
* fix bug in the classes checker which was making pylint crash if
"object" is assigned in a class inheriting from it (test
func_noerror_object_as_class_attribute)
* fix problem with the similar checker when related options are
defined in a configuration file
* new --generate-man option to generate pylint's man page (require the
latest logilab.common (>= 0.9.3)
* packaged (generated...) man page
What's New in Pylint 0.6.3?
===========================
Release date: 2005-02-24
* fix scope problem which may cause false positive and true negative
on E0602
* fix problem with some options such as disable-msg causing error when
they are coming from the configuration file
What's New in Pylint 0.6.2?
============================
Release date: 2005-02-16
* fix false positive on E0201 ("access to undefined member") with
metaclasses
* fix false positive on E0203 ("access to member before its
definition") when attributes are defined in a parent class
* fix false positive on W0706 ("identifier used to raise an exception
assigned to...")
* fix interpretation of ``\t`` as value for the indent-string
configuration variable
* fix --rcfile so that --rcfile=pylintrc (only --rcfile pylintrc was
working in earlier release)
* new raw checker example in the examples/ directory
What's New in Pylint 0.6.1?
===========================
Release date: 2005-02-04
* new --rcfile option to specify the configuration file without the
PYLINTRC environment variable
* added an example module for a custom pylint checker (see the
example/ directory)
* some fixes to handle fixes in common 0.9.1 (should however still working
with common 0.9.0, even if upgrade is recommended)
What's New in Pylint 0.6.0?
===========================
Release date: 2005-01-20
* refix pylint Emacs mode
* no more traceback when just typing "pylint"
* fix a bug which may cause crashes on resolving parent classes
* fix problems with the format checker: don't chock on files
containing multiple CR, avoid C0322, C0323, C0324 false positives
with triple quoted string with quote inside
* correctly detect access to member defined latter in __init__ method
* now depends on common 0.8.1 to fix problem with interface resolution
(Closes #8606)
* new --list-msgs option describing available checkers and their
messages
* added windows specific documentation to the README file, contributed
by Brian van den Broek
* updated doc/features.txt (actually this file is now generated using
the --list-msgs option), more entries into the FAQ
* improved tests coverage
What's New in Pylint 0.5.0?
===========================
Release date: 2004-10-19
* avoid importing analyzed modules !
* new Refactor and Convention message categories. Some Warnings have been
remapped into those new categories
* added "similar", a tool to find copied and pasted lines of code,
both using a specific command line tool and integrated as a
pylint's checker
* imports checker may report import dependencies as a dot graph
* new checker regrouping most Refactor detection (with some new metrics)
* more command line options storable in the configuration file
* fix bug with total / undocumented number of methods
What's New in Pylint 0.4.2?
===========================
Release date: 2004-07-08
* fix pylint Emacs mode
* fix classes checkers to handler twisted interfaces
What's New in Pylint 0.4.1?
===========================
Release date: 2004-05-14
* fix the setup.py script to allow bdist_winst (well, the generated
installer has not been tested...) with the necessary
logilab/__init__.py file
* fix file naming convention as suggested by Andreas Amoroso
* fix stupid crash bug with bad method names
What's New in Pylint 0.4.0?
===========================
Release date: 2004-05-10
* fix file path with --parsable
* --parsable option has been renamed to --parseable
* added patch from Andreas Amoroso to output message to files instead
of standard output
* added Run to the list of correct variable names
* fix variable names regexp and checking of local classes names
* some basic handling of metaclasses
* no-docstring-rgx apply now on classes too
* new option to specify a different regexp for methods than for
functions
* do not display the evaluation report when no statements has been
analysed
* fixed crash with a class nested in a method
* fixed format checker to deals with triple quoted string and
lines with code and comment mixed
* use logilab.common.ureports to layout reports
What's New in Pylint 0.3.3?
===========================
Release date: 2004-02-17
* added a parsable text output, used when the --parsable option is
provided
* added an Emacs mode using this output, available in the distrib's
elisp directory
* fixed some typos in messages
* change include-ids options to yn, and allow it to be in the
configuration file
* do not chock on corrupted stats files
* fixed bug in the format checker which may stop pylint execution
* provide scripts for unix and windows to wrap the minimal pylint tk
gui
What's New in Pylint 0.3.2?
===========================
Release date: 2003-12-23
* html-escape messages in the HTML reporter (bug reported by Juergen
Hermann)
* added "TODO" to the list of default note tags
* added "rexec" to the list of default deprecated modules
* fixed typos in some messages
What's New in Pylint 0.3.1?
===========================
Release date: 2003-12-05
* bug fix in format and classes checkers
* remove print statement from imports checkers
* provide a simple tk gui, essentially useful for windows users
What's New in Pylint 0.3.0?
===========================
Release date: 2003-11-20
* new exceptions checker, checking for string exception and empty
except clauses.
* imports checker checks for reimport of modules
* classes checker checks for calls to ancestor's __init__ and abstract
method not overridden. It doesn't complain anymore for unused import in
__init__ files, and provides a new option ignore-interface-methods,
useful when you're using zope Interface implementation in your project
* base checker checks for disallowed builtins call (controlled by the
bad-functions option) and for use of * and **
* format checker checks for use of <> and "l" as long int marker
* major internal API changes
* use the rewrite of astng, based on compiler.ast
* added unique id for messages, as suggested by Wolfgang Grafen
* added unique id for reports
* can take multiple modules or files as argument
* new options command line options : --disable-msg, --enable-msg,
--help-msg, --include-ids, --reports, --disable-report, --cache-size
* --version shows the version of the python interpreter
* removed some options which are now replaced by [en|dis]able-msg, or
disable-report
* read disable-msg and enable-msg options in source files (should be
in comments on the top of the file, in the form
"# pylint: disable-msg=W0402"
* new message for modules importing themselves instead of the "cyclic
import" message
* fix bug with relative and cyclic imports
* fix bug in imports checker (cycle was not always detected)
* still fixes in format checker : don't check comment and docstring,
check first line after an indent
* allowed/prohibited names now apply to all identifiers, not only
variables, so changed the configuration option from
(good|bad)-variable-names to (good|bad)-names
* added string, rexec and Bastion to the default list of deprecated
modules
* do not print redefinition warning for function/class/method defined
in mutually exclusive branches
What's New in Pylint 0.2.1?
===========================
Release date: 2003-10-10
* added some documentation, fixed some typos
* set environment variable PYLINT_IMPORT to 1 during pylint execution.
* check that variables "imported" using the global statement exist
* indentation problems are now warning instead of errors
* fix checkers.initialize to try to load all files with a known python
extension (patch from wrobell)
* fix a bunch of messages
* fix sample configuration file
* fix the bad-construction option
* fix encoding checker
* fix format checker
What's New in Pylint 0.2.0?
===========================
Release date: 2003-09-12
* new source encoding / FIXME checker (pep 263)
* new --zope option which trigger Zope import. Useful to check Zope
products code.
* new --comment option which enable the evaluation note comment
(disabled by default).
* a ton of bug fixes
* easy functional test infrastructure
What's New in Pylint 0.1.2?
===========================
Release date: 2003-06-18
* bug fix release
* remove dependency to pyreverse
What's New in Pylint 0.1.1?
===========================
Release date: 2003-06-01
* much more functionalities !
What's New in Pylint 0.1?
===========================
Release date: 2003-05-19
* initial release
---
### Doc Whatsnew 0 Index (`doc/whatsnew/0/index.rst`)
0.x
===
.. include:: ../full_changelog_explanation.rst
Ticket numbers are almost always internal to Logilab, some come from bitbucket.
.. toctree::
:maxdepth: 2
0.x.rst
---
### Doc Whatsnew 1 1.0 (`doc/whatsnew/1/1.0.rst`)
**************************
What's New In Pylint 1.0
**************************
Release date: 2013-08-06
* Add check for the use of 'exec' function
* New --msg-template option to control output, deprecating "msvc" and
"parseable" output formats as well as killing ``--include-ids`` and ``--symbols``
options
* Do not emit [fixme] for every line if the config value 'notes'
is empty, but [fixme] is enabled.
* Emit warnings about lines exceeding the column limit when
those lines are inside multiline docstrings.
* Do not double-check parameter names with the regex for parameters and
inline variables.
* Added a new warning :ref:`missing-final-newline` for files missing
the final newline.
* Methods that are decorated as properties are now treated as attributes
for the purposes of name checking.
* Names of derived instance class member are not checked any more.
* Names in global statements are now checked against the regular
expression for constants.
* For toplevel name assignment, the class name regex will be used if
pylint can detect that value on the right-hand side is a class
(like collections.namedtuple()).
* Simplified :ref:`invalid-name` message
* Added a new warning invalid-encoded-data (W0512) for files that
contain data that cannot be decoded with the specified or
default encoding.
* New warning :ref:`bad-open-mode` for calls to open (or file) that
specify invalid open modes (Original implementation by Sasha Issayev).
* New warning old-style-class (C1001) for classes that do not have any
base class.
* Add new name type 'class_attribute' for attributes defined
in class scope. By default, allow both const and variable names.
* New warning :ref:`trailing-whitespace` that warns about
trailing whitespace.
* Added a new warning unpacking-in-except (W0712) about unpacking
exceptions in handlers, which is unsupported in Python 3.
* Add a configuration option for :ref:`missing-docstring` to
optionally exempt short functions/methods/classes from
the check.
* Add the type of the offending node to :ref:`missing-docstring`
and :ref:`empty-docstring`.
* New utility classes for per-checker unittests in testutils.py
* Do not warn about redefinitions of variables that match the
dummy regex.
* Do not treat all variables starting with _ as dummy variables,
only _ itself.
* Make the :ref:`line-too-long` warning configurable by adding a regex for lines
for with the length limit should not be enforced
* Do not warn about a long line if a pylint disable
option brings it above the length limit
* Do not flag names in nested with statements as undefined.
* Added a new warning 'old-raise-syntax' for the deprecated syntax
raise Exception, args
* Support for PEP 3102 and new :ref:`missing-kwoa` message for missing
mandatory keyword argument
Closes Logilab #107788
* Fix spelling of max-branchs option, now max-branches
* Added a new base class and interface for checkers that work on the
tokens rather than the syntax, and only tokenize the input file
once.
* Follow astng renaming to astroid
* Check for unbalanced unpacking in assignments
Closes BitBucket #37
* Fix incomplete-protocol false positive for read-only containers like tuple
Closes BitBucket #25
* Fix False positive E1003 on Python 3 for argument-less super()
Closes BitBucket #16
* Put back documentation in source distribution
Closes BitBucket #6
* epylint shouldn't hang anymore when there is a large output on pylint'stderr
Closes BitBucket #15
* Fix epylint w/ python3
Closes BitBucket #7
* Remove string module from the default list of deprecated modules
Closes BitBucket #3
---
### Doc Whatsnew 1 1.1 (`doc/whatsnew/1/1.1.rst`)
**************************
What's New In Pylint 1.1
**************************
Release date: 2013-12-22
* Add new check for use of :ref:`deprecated-pragma` directives "pylint:disable-msg"
or "pylint:enable-msg" which was previously emitted as a regular warn().
* Avoid false :ref:`used-before-assignment` for except handler defined
identifier used on the same line.
Closes #111
* Combine 'no-space-after-operator', 'no-space-after-comma' and
'no-space-before-operator' into a new warning 'bad-whitespace'.
* Add a new warning :ref:`superfluous-parens` for unnecessary
parentheses after certain keywords.
* Fix a potential crash in the redefine-in-handler warning
if the redefined name is a nested getattr node.
* Add a new option for the multi-statement warning to
allow single-line if statements.
* Add :ref:`bad-context-manager` error, checking that '__exit__'
special method accepts the right number of arguments.
* Run pylint as a python module 'python -m pylint' (Anatoly Techtonik).
* Check for non-exception classes inside an except clause.
* epylint support options to give to pylint after the file to analyze and
have basic input validation, patches provided by
felipeochoa and Brian Lane.
Closes BitBucket #53
Closes BitBucket #54
* Added a new warning, :ref:`non-iterator-returned`, for non-iterators
returned by '__iter__'.
* Add new checks for unpacking non-sequences in assignments
(:ref:`unpacking-non-sequence`) as well as unbalanced tuple unpacking
(:ref:`unbalanced-tuple-unpacking`).
* :ref:`useless-else-on-loop` not emitted if there is a break in the
else clause of inner loop.
Closes #117
* don't mark ``input`` as a bad function when using python3.
Closes #110
* badly-implemented-container caused several problems in its
current implementation. Deactivate it until we have something
better.
Refs #112
* Use attribute regexp for properties in python3, as in python2
* Create the ``PYLINTHOME`` directory when needed, it might fail and lead to
spurious warnings on import of pylint.config.
* Fix setup.py so that pylint properly install on Windows when using python3
* Various documentation fixes and enhancements
* Fix a false-positive :ref:`trailing-whitespace` on Windows
Closes #55
---
### Doc Whatsnew 1 1.2 (`doc/whatsnew/1/1.2.rst`)
**************************
What's New In Pylint 1.2
**************************
Release date: 2014-04-30
* Restore the ability to specify the init-hook option via the
configuration file, which was accidentally broken in 1.2.0.
* Add a new warning [bad-continuation] for badly indented continued
lines.
* Emit :ref:`assignment-from-none` when the function contains bare returns.
Closes BitBucket #191
* Added a new warning for closing over variables that are
defined in loops.
Closes BitBucket #176
* Do not warn about ``\u`` escapes in string literals when Unicode literals
are used for Python 2.*.
Closes BitBucket #151
* Extend the checking for :ref:`unbalanced-tuple-unpacking` and
:ref:`unpacking-non-sequence` to instance attribute unpacking as well.
* Fix explicit checking of python script (1.2 regression)
Closes #219
* Restore --init-hook, renamed accidentally into --init-hooks in 1.2.0
Closes #211
* Add 'indexing-exception' warning, which detects that indexing
an exception occurs in Python 2 (behaviour removed in Python 3).
What's New in Pylint 1.2.0?
===========================
Release date: 2014-04-18
* Pass the current python paths to pylint process when invoked via
epylint.
Closes BitBucket #133.
* Add -i / --include-ids and -s / --symbols back as completely ignored
options.
Closes BitBucket #180.
* Extend the number of cases in which logging calls are detected.
Closes BitBucket #182.
* Improve pragma handling to not detect pylint:* strings in non-comments.
Closes BitBucket #79.
* Do not crash with UnknownMessage if an unknown message ID/name appears
in disable or enable in the configuration. Patch by Cole Robinson.
Closes BitBucket #170
* Add new warning :ref:`eval-used`, checking that the builtin function ``eval`` was used.
* Make it possible to show a naming hint for invalid name by setting
include-naming-hint. Also make the naming hints configurable.
Closes BitBucket #138
* Added support for enforcing multiple, but consistent name styles for
different name types inside a single module; based on a patch written
by [email protected].
* Also warn about empty docstrings on overridden methods; contributed
by [email protected].
* Also inspect arguments to constructor calls, and emit relevant
warnings; contributed by [email protected].
* Added a new configuration option logging-modules to make the list
of module names that can be checked for :ref:`logging-not-lazy` et. al.
configurable; contributed by [email protected].
* ensure init-hooks is evaluated before other options, notably load-plugins
Closes #166
* Python 2.5 support restored: fixed small issues preventing pylint to run
on python 2.5.
Closes BitBucket #50
Closes BitBucket #62
* pylint doesn't crash when looking for :ref:`used-before-assignment` in context manager assignments.
Closes BitBucket #128
* Add new warning, :ref:`bad-reversed-sequence`, for checking that the
reversed() builtin receive a sequence (implements ``__getitem__`` and ``__len__``,
without being a dict or a dict subclass) or an instance which implements
``__reversed__``.
* Mark ``file`` as a bad function when using python2
Closes #8
* Add new warning :ref:`bad-exception-context`, checking
that ``raise ... from ...`` uses a proper exception context
(None or an exception).
* Enhance the check for :ref:`used-before-assignment` to look
for 'nonlocal' uses.
* Emit :ref:`undefined-all-variable` if a package's __all__
variable contains a missing submodule.
Closes #126
* Add a new warning :ref:`abstract-class-instantiated` for checking
that abstract classes created with ``abc`` module and
with abstract methods are instantiated.
* Do not warn about :ref:`return-arg-in-generator` in Python 3.3+.
* Do not warn about :ref:`abstract-method` when the abstract method
is implemented through assignment
Closes #155
* Improve cyclic import detection in the case of packages, patch by Buck Golemon
* Add new warnings for checking proper class __slots__:
``invalid-slots-object`` and ``invalid-slots``.
* Search for rc file in `~/.config/pylintrc` if `~/.pylintrc`
doesn't exists
Closes #121
* Don't register the new style checker w/ python >= 3
* Fix :ref:`unused-import` false positive w/ augment assignment
Closes #78
* Fix :ref:`access-member-before-definition` false negative wrt aug assign
Closes #164
* Do not attempt to analyze non python file, e.g. .so file
Closes #122
---
### Doc Whatsnew 1 1.3 (`doc/whatsnew/1/1.3.rst`)
**************************
What's New In Pylint 1.3
**************************
Release date: 2014-07-26
* Allow hanging continued indentation for implicitly concatenated
strings.
Closes #232.
* Pylint works under Python 2.5 again, and its test suite passes.
* Fix some false positives for the cellvar-from-loop warnings.
Closes #233.
* Return new astroid class nodes when the inferencer can detect that
that result of a function invocation on a type (like ``type`` or
`abc.ABCMeta`) is requested.
Closes #205.
* Emit :ref:`undefined-variable` for undefined names when using the
Python 3 ``metaclass=`` argument.
* Checkers respect priority now.
Closes #229
* Fix a false positive regarding W0511.
Closes #149.
* Fix :ref:`unused-import` false positive with Python 3 metaclasses
Closes #143
* Don't warn with :ref:`bad-format-character` when encountering
the 'a' format on Python 3.
* Add multiple checks for PEP 3101 advanced string formatting:
:ref:`bad-format-string`, :ref:`missing-format-argument-key`,
:ref:`unused-format-string-argument`, :ref:`format-combined-specification`,
:ref:`missing-format-attribute` and :ref:`invalid-format-index`.
* Issue :ref:`broad-except` and :ref:`bare-except` even if the number
of except handlers is different than 1.
Closes #113
* Issue :ref:`attribute-defined-outside-init` for all cases, not just
for the last assignment.
Closes #262
* Emit :ref:`not-callable` when calling properties.
Closes #268.
* Fix a false positive with unbalanced iterable unpacking,
when encountering starred nodes.
Closes #273.
* Add new checks, :ref:`invalid-slice-index` and :ref:`invalid-sequence-index`
for invalid sequence and slice indices.
* Add :ref:`assigning-non-slot` warning, which detects assignments to
attributes not defined in slots.
* Don't emit :ref:`no-name-in-module` for ignored modules.
Closes #223.
* Fix an :ref:`unused-variable` false positive, where the variable is
assigned through an import.
Closes #196.
* Definition order is considered for classes, function arguments
and annotations.
Closes #257.
* Don't emit :ref:`unused-variable` when assigning to a nonlocal.
Closes #275.
* Do not let ImportError propagate from the import checker, leading to crash
in some namespace package related cases.
Closes #203.
* Don't emit :ref:`pointless-string-statement` for attribute docstrings.
Closes #193.
* Use the proper mode for pickle when opening and writing the stats file.
Closes #148.
* Don't emit hidden-method message when the attribute has been
monkey-patched, you're on your own when you do that.
* Only emit :ref:`attribute-defined-outside-init` for definition within the same
module as the offended class, avoiding to mangle the output in some cases.
* Don't emit :ref:`unnecessary-lambda` if the body of the lambda call contains
call chaining.
Closes #243.
* Don't emit :ref:`missing-docstring` when the actual docstring uses ``.format``.
Closes #281.
---
### Doc Whatsnew 1 1.4 (`doc/whatsnew/1/1.4.rst`)
**************************
What's New In Pylint 1.4
**************************
What's New in Pylint 1.4.3?
===========================
Release date: 2015-03-14
* Remove three warnings: star-args, abstract-class-little-used,
abstract-class-not-used. These warnings don't add any real value
and they don't imply errors or problems in the code.
* Added a new option for controlling the peephole optimizer in astroid.
The option ``--optimize-ast`` will control the peephole optimizer,
which is used to optimize a couple of AST subtrees. The current problem
solved by the peephole optimizer is when multiple joined strings,
with the addition operator, are encountered. If the numbers of such
strings is high enough, Pylint will then fail with a maximum recursion
depth exceeded error, due to its visitor architecture. The peephole
just transforms such calls, if it can, into the final resulting string
and this exhibit a problem, because the visit_binop method stops being
called (in the optimized AST it will be a Const node).
What's New in Pylint 1.4.2?
===========================
Release date: 2015-03-11
* Don't require a docstring for empty modules.
Closes #261
* Fix a false positive with ``too-few-format-args`` string warning,
emitted when the string format contained a normal positional
argument ('{0}'), mixed with a positional argument which did
an attribute access ('{0.__class__}').
Closes #463
* Take in account all the methods from the ancestors
when checking for :ref:`too-few-public-methods`.
Closes #471
* Catch enchant errors and emit :ref:`invalid-characters-in-docstring`
when checking for spelling errors.
Closes #469
* Use all the inferred statements for the :ref:`super-init-not-called`
check.
Closes #389
* Add a new warning, 'unichr-builtin', emitted by the Python 3
porting checker, when the unichr builtin is found.
Closes #472
* Add a new warning, 'intern-builtin', emitted by the Python 3
porting checker, when the intern builtin is found.
Closes #473
* Add support for editable installations.
* The HTML output accepts the ``--msg-template`` option. Patch by
Dan Goldsmith.
* Add 'map-builtin-not-iterating' (replacing 'implicit-map-evaluation'),
'zip-builtin-not-iterating', 'range-builtin-not-iterating', and
'filter-builtin-not-iterating' which are emitted by ``--py3k`` when the
appropriate built-in is not used in an iterating context (semantics
taken from 2to3).
* Add a new warning, :ref:`unidiomatic-typecheck`, emitted when an explicit
typecheck uses type() instead of isinstance(). For example,
`type(x) == Y` instead of `isinstance(x, Y)`. Patch by Chris Rebert.
Closes #299
* Add support for combining the Python 3 checker mode with the --jobs
flag (--py3k and --jobs).
Closes #467
* Add a new warning for the Python 3 porting checker, 'using-cmp-argument',
emitted when the ``cmp`` argument for the ``list.sort`` or ``sorted builtin``
is encountered.
* Make the --py3k flag commutative with the -E flag. Also, this patch
fixes the leaks of error messages from the Python 3 checker when
the errors mode was activated.
Closes #437
What's New in Pylint 1.4.1?
===========================
Release date: 2015-01-16
* Look only in the current function's scope for :ref:`bad-super-call`.
Closes #403
* Check the return of properties when checking for :ref:`not-callable`.
Closes #406
* Warn about using the input() or round() built-ins for Python 3.
Closes #411
* Proper abstract method lookup while checking for :ref:`abstract-class-instantiated`.
Closes #401
* Use a mro traversal for finding abstract methods.
Closes #415
* Fix a false positive with :ref:`catching-non-exception` and tuples of exceptions.
* Fix a false negative with :ref:`raising-non-exception`, when the raise used
an uninferrable exception context.
* Fix a false positive on Python 2 for :ref:`raising-bad-type`, when
raising tuples in the form 'raise (ZeroDivisionError, None)'.
* Fix a false positive with invalid-slots-objects, where the slot entry
was a unicode string on Python 2.
Closes #421
* Add a new warning, :ref:`redundant-unittest-assert`, emitted when using
unittest's methods assertTrue and assertFalse with constant value
as argument. Patch by Vlad Temian.
* Add a new JSON reporter, usable through -f flag.
* Add the method names for the :ref:`signature-differs` and 'argument-differs'
warnings.
Closes #433
* Don't compile test files when installing.
* Fix a crash which occurred when using multiple jobs and the files
given as argument didn't exist at all.
What's New in Pylint 1.4.0?
===========================
Release date: 2014-11-23
* Added new options for controlling the loading of C extensions.
By default, only C extensions from the stdlib will be loaded
into the active Python interpreter for inspection, because they
can run arbitrary code on import. The option
``--extension-pkg-whitelist`` can be used to specify modules
or packages that are safe to load.
* Change default max-line-length to 100 rather than 80
* Drop BaseRawChecker class which were only there for backward
compatibility for a while now
* Don't try to analyze string formatting with objects coming from
function arguments.
Closes #373
* Port source code to be Python 2/3 compatible. This drops the
need for 2to3, but does drop support for Python 2.5.
* Each message now comes with a confidence level attached, and
can be filtered base on this level. This allows to filter out
all messages that were emitted even though an inference failure
happened during checking.
* Improved presenting :ref:`unused-import` message.
Closes #293
* Add new checker for finding spelling errors. New messages:
:ref:`wrong-spelling-in-comment`, :ref:`wrong-spelling-in-docstring`.
New options: spelling-dict, spelling-ignore-words.
* Add new '-j' option for running checks in sub-processes.
* Added new checks for line endings if they are mixed (LF vs CRLF)
or if they are not as expected. New messages: :ref:`mixed-line-endings`,
:ref:`unexpected-line-ending-format`. New option: expected-line-ending-format.
* :ref:`dangerous-default-value` no longer evaluates the value of the arguments,
which could result in long error messages or sensitive data being leaked.
Closes #282
* Fix a false positive with string formatting checker, when
encountering a string which uses only position-based arguments.
Closes #285
* Fix a false positive with string formatting checker, when using
keyword argument packing.
Closes #288
* Proper handle class level scope for lambdas.
* Handle :ref:`too-few-format-args` or :ref:`too-many-format-args` for format
strings with both named and positional fields.
Closes #286
* Analyze only strings by the string format checker.
Closes #287
* Properly handle nested format string fields.
Closes #294
* Don't emit :ref:`attribute-defined-outside-init` if the attribute
was set by a function call in a defining method.
Closes #192
* Properly handle unicode format strings for Python 2.
Closes #296
* Don't emit :ref:`import-error` if an import was protected by a try-except,
which excepted ImportError.
* Fix an :ref:`unused-import` false positive, when the error was emitted
for all the members imported with 'from import' form.
Closes #304
* Don't emit :ref:`invalid-name` when assigning a name in an
ImportError handler.
Closes #302
* Don't count branches from nested functions.
* Fix a false positive with :ref:`too-few-format-args`, when the format
strings contains duplicate manual position arguments.
Closes #310
* fixme regex handles comments without spaces after the hash.
Closes #311
* Don't emit :ref:`unused-import` when a special object is imported
(__all__, __doc__ etc.).
Closes #309
* Look in the metaclass, if defined, for members not found in the current
class.
Closes #306
* Don't emit :ref:`protected-access` if the attribute is accessed using
a property defined at the class level.
* Detect calls of the parent's __init__, through a binded super() call.
* Check that a class has an explicitly defined metaclass before
emitting 'old-style-class' for Python 2.
* Emit :ref:`catching-non-exception` for non-class nodes.
Closes #303
* Order of reporting is consistent.
* Add a new warning, :ref:`boolean-datetime`, emitted when an instance
of 'datetime.time' is used in a boolean context.
Closes #239
* Fix a crash which occurred while checking for :ref:`method-hidden`,
when the parent frame was something different than a function.
* Generate html output for missing files.
Closes #320
* Fix a false positive with :ref:`too-many-format-args`, when the format
string contains mixed attribute access arguments and manual
fields.
Closes #322
* Extend the cases where :ref:`undefined-variable` and :ref:`used-before-assignment`
can be detected.
Closes #291
* Add support for customising callback identifiers, by adding a new
'--callbacks' command line option.
Closes #326
* Add a new warning, :ref:`logging-format-interpolation`, emitted when .format()
string interpolation is used within logging function calls.
* Don't emit :ref:`unbalanced-tuple-unpacking` when the rhs of the assignment
is a variable length argument.
Closes #329
* Add a new warning, :ref:`inherit-non-class`, emitted when a class inherits
from something which is not a class.
Closes #331
* Fix another false positives with :ref:`undefined-variable`, where the variable
can be found as a class assignment and used in a function annotation.
Closes #342
* Handle assignment of the string format method to a variable.
Closes #351
* Support wheel packaging format for PyPi.
Closes #334
* Check that various built-ins that do not exist in Python 3 are not
used: apply, basestring, buffer, cmp, coerce, execfile, file, long
raw_input, reduce, StandardError, unicode, reload and xrange.
* Warn for magic methods which are not used in any way in Python 3:
__coerce__, __delslice__, __getslice__, __setslice__, __cmp__,
__oct__, __nonzero__ and __hex__.
* Don't emit :ref:`assigning-non-slot` when the assignment is for a property.
Closes #359
* Fix for regression: '{path}' was no longer accepted in '--msg-template'.
* Report the percentage of all messages, not just for errors and warnings.
Closes #319
* :ref:`too-many-public-methods` is reported only for methods defined in a class,
not in its ancestors.
Closes #248
* :ref:`too-many-lines` disable pragma can be located on any line, not only the
first.
Closes #321
* Warn in Python 2 when an import statement is found without a
corresponding ``from __future__ import absolute_import``.
* Warn in Python 2 when a non-floor division operation is found without
a corresponding ``from __future__ import division``.
* Add a new option, 'exclude-protected', for excluding members
from the :ref:`protected-access` warning.
Closes #48
* Warn in Python 2 when using dict.iter*(), dict.view*(); none of these
methods are available in Python 3.
* Warn in Python 2 when calling an object's next() method; Python 3 uses
__next__() instead.
* Warn when assigning to __metaclass__ at a class scope; in Python 3 a
metaclass is specified as an argument to the 'class' statement.
* Warn when performing parameter tuple unpacking; it is not supported in
Python 3.
* :ref:`abstract-class-instantiated` is also emitted for Python 2.
It was previously disabled.
* Add 'long-suffix' error, emitted when encountering the long suffix
on numbers.
* Add support for disabling a checker, by specifying an 'enabled'
attribute on the checker class.
* Add a new CLI option, --py3k, for enabling Python 3 porting mode. This
mode will disable all other checkers and will emit warnings and
errors for constructs which are invalid or removed in Python 3.
* Add 'old-octal-literal' to Python 3 porting checker, emitted when
encountering octals with the old syntax.
* Add 'implicit-map-evaluation' to Python 3 porting checker, emitted
when encountering the use of map builtin, without explicit evaluation.
---
### Doc Whatsnew 1 1.5 (`doc/whatsnew/1/1.5.rst`)
**************************
What's New In Pylint 1.5
**************************
What's New in Pylint 1.5.5?
===========================
Release date: 2016-03-21
* Let visit_importfrom from Python 3 porting checker be called when everything is disabled
Because the visit method was filtering the patterns it was expecting to be activated,
it didn't run when everything but one pattern was disabled, leading to spurious false
positives
Closes #852
* Don't emit unsubscriptable-value for classes with unknown
base classes.
Closes #776.
* Use an OrderedDict for storing the configuration elements
This fixes an issue related to impredictible order of the disable / enable
elements from a config file. In certain cases, the disable was coming before
the enable which resulted in classes of errors to be enabled, even though the intention
was to disable them. The best example for this was in the context of running multiple
processes, each one of it having different enables / disables that affected the output.
Closes #815
* Don't consider bare and broad except handlers as ignoring NameError,
AttributeError and similar exceptions, in the context of checkers for
these issues.
Closes #826
What's New in Pylint 1.5.4?
===========================
Release date: 2016-01-15
* Merge StringMethodChecker with StringFormatChecker. This fixes a
bug where disabling all the messages and enabling only a handful of
messages from the StringFormatChecker would have resulted in no
messages at all.
* Don't apply :ref:`unneeded-not` over sets.
What's New in Pylint 1.5.3?
===========================
Release date: 2016-01-11
* Handle the import fallback idiom with regard to :ref:`wrong-import-order`.
Closes #750
* Decouple the displaying of reports from the displaying of messages
Some reporters are aggregating the messages instead of displaying
them when they are available. The actual displaying was conflatted
in the generate_reports. Unfortunately this behaviour was flaky
and in the case of the JSON reporter, the messages weren't shown
at all if a file had syntax errors or if it was missing.
In order to fix this, the aggregated messages can now be
displayed with Reporter.display_message, while the reports are
displayed with display_reports.
Closes #766
Closes #765
* Ignore function calls with variadic arguments without a context.
Inferring variadic positional arguments and keyword arguments
will result into empty Tuples and Dicts, which can lead in
some cases to false positives with regard to :ref:`no-value-for-parameter`.
In order to avoid this, until we'll have support for call context
propagation, we're ignoring such cases if detected.
Closes #722
* Treat AsyncFunctionDef just like FunctionDef nodes,
by implementing visit_asyncfunctiondef in terms of
visit_functiondef.
Closes #767
* Take in account kwonlyargs when verifying that arguments
are defined with the check_docs extension.
Closes #745
* Suppress reporting :ref:`unneeded-not` inside ``__ne__`` methods
Closes #749
What's New in Pylint 1.5.2?
===========================
Release date: 2015-12-21
* Don't crash if graphviz is not installed, instead emit a
warning letting the user to know.
Closes #168
* Accept only functions and methods for the :ref:`deprecated-method` checker.
This prevents a crash which can occur when an object doesn't have
.qname() method after the inference.
* Don't emit super-on-old-class on classes with unknown bases.
Closes #721
* Allow statements in ``if`` or ``try`` blocks containing imports.
Closes #714
What's New in Pylint 1.5.1?
===========================
Release date: 2015-12-02
* Fix a crash which occurred when old visit methods are encountered
in plugin modules.
Closes #711
* Add :ref:`wrong-import-position` to check_messages's decorator arguments
for ImportChecker.leave_module
This fixes an esoteric bug which occurs when :ref:`ungrouped-imports` and
:ref:`wrong-import-order` are disabled and pylint is executed on multiple files.
What happens is that without :ref:`wrong-import-position` in check_messages,
leave_module will never be called, which means that the first non-import node
from other files might leak into the current file,
leading to :ref:`wrong-import-position` being emitted by pylint.
* Fix a crash which occurred when old visit methods are encountered
in plugin modules.
Closes #711
* Don't emit :ref:`import-self` and :ref:`cyclic-import` for relative imports
of modules with the same name as the package itself.
Closes #708
Closes #706.
What's New in Pylint 1.5.0?
===========================
Release date: 2015-11-29
* Added multiple warnings related to imports. :ref:`wrong-import-order`
is emitted when PEP 8 recommendations regarding imports are not
respected (that is, standard imports should be followed by third-party
imports and then by local imports). :ref:`ungrouped-imports` is emitted
when imports from the same package or module are not placed
together, but scattered around in the code. :ref:`wrong-import-position`
is emitted when code is mixed with imports, being recommended for the
latter to be at the top of the file, in order to figure out easier by
a human reader what dependencies a module has.
Closes #692
* Added a new refactoring warning, :ref:`unneeded-not`, emitted
when an expression with the not operator could be simplified.
Closes #670
* Added a new refactoring warning, :ref:`simplifiable-if-statement`,
used when an if statement could be reduced to a boolean evaluation
of its test.
Closes #698
* Added a new refactoring warning, :ref:`too-many-boolean-expressions`,
used when an if statement contains too many boolean expressions,
which makes the code less maintainable and harder to understand.
Closes #677
* Property methods are shown as attributes instead of functions in
pyreverse class diagrams.
Closes #284
* Add a new refactoring error, :ref:`too-many-nested-blocks`, which is emitted
when a function or a method has too many nested blocks, which makes the
code less readable and harder to understand.
Closes #668
* Add a new error, :ref:`unsubscriptable-object`, that is emitted when
value used in subscription expression doesn't support subscription
(i.e. doesn't define __getitem__ method).
* Don't warn about abstract classes instantiated in their own body.
Closes #627
* Obsolete options are not present by default in the generated
configuration file.
Closes #632
* :ref:`non-iterator-returned` can detect classes with iterator-metaclasses.
Closes #679
* Add a new error, :ref:`unsupported-membership-test`, emitted when value
to the right of the 'in' operator doesn't support membership test
protocol (i.e. doesn't define __contains__/__iter__/__getitem__)
* Add new errors, :ref:`not-an-iterable`, emitted when non-iterable value
is used in an iterating context (starargs, for-statement,
comprehensions, etc), and :ref:`not-a-mapping`, emitted when non-mapping
value is used in a mapping context.
Closes #563
* Make :ref:`no-self-use` checker not emit a warning if there is a 'super()'
call inside the method.
Closes #667
* Add checker to identify multiple imports on one line.
Closes #598
* Fix :ref:`unused-argument` false positive when the "+=" operator is used.
Closes #518
* Don't emit :ref:`import-error` for ignored modules. PyLint will not emit import
errors for any import which is, or is a subpackage of, a module in
the ignored-modules list.
Closes #223
* Fix :ref:`unused-import` false positive when the import is used in a
class assignment.
Closes #475
* Add a new error, :ref:`not-context-manager`, emitted when something
that doesn't implement __enter__ and __exit__ is used in a with
statement.
* Add a new warning, :ref:`confusing-with-statement`, emitted by the
base checker, when an ambiguous looking with statement is used.
For example `with open() as first, second` which looks like a
tuple assignment but is actually 2 context managers.
* Add a new warning, :ref:`duplicate-except`, emitted when there is an
exception handler which handles an exception type that was handled
before.
Closes #485
* A couple of warnings got promoted to errors, since they could uncover
potential bugs in the code. These warnings are: :ref:`assignment-from-none`,
:ref:`unbalanced-tuple-unpacking`, :ref:`unpacking-non-sequence`, :ref:`non-iterator-returned`.
Closes #388
* Allow ending a pragma control with a semicolon. In this way, users
can continue a pragma control with a reason for why it is used,
as in `# pylint: disable=old-style-class;reason=...`.
Closes #449
* --jobs can be used with --load-plugins now.
Closes #456
* Improve the performance of --jobs when dealing only with a package name.
Closes #479
* Don't emit an :ref:`unused-wildcard-import` when the imported name comes
from another module and it is in fact a __future__ name.
* The colorized reporter now works on Windows.
Closes #96.
* Remove pointless-except warning. It was previously disabled by
default and it wasn't very useful.
Closes #506.
* Fix a crash on Python 3 related to the string checker, which
crashed when it encountered a bytes string with a .format
method called.
* Don't warn about :ref:`no-self-use` for builtin properties.
* Fix a false positive for :ref:`bad-reversed-sequence`, when a subclass
of a ``dict`` provides a __reversed__ method.
* Change the default no-docstring-rgx so :ref:`missing-docstring` isn't
emitted for private functions.
* Don't emit :ref:`redefined-outer-name` for __future__ directives.
Closes #520.
* Provide some hints for the :ref:`bad-builtin` message.
Closes #522.
* When checking for invalid arguments to a callable, in typecheck.py,
look up for the __init__ in case the found __new__ comes from builtins.
Since the __new__ comes from builtins, it will not have attached any
information regarding what parameters it expects, so the check
will be useless. Retrieving __init__ in that case will at least
detect a couple of false negatives.
Closes #429.
* Don't emit :ref:`no-member` for classes with unknown bases.
Since we don't know what those bases might add, we simply ignore
the error in this case.
* Lookup in the implicit metaclass when checking for :ref:`no-member`,
if the class in question has an implicit metaclass, which is
True for new style classes.
Closes #438.
* Add two new warnings, :ref:`duplicate-bases` and :ref:`inconsistent-mro`.
:ref:`duplicate-bases` is emitted when a class has the same bases
listed more than once in its bases definition, while :ref:`inconsistent-mro`
is emitted when no sane mro hierarchy can be determined.
Closes #526.
* Remove interface-not-implemented warning.
Closes #532.
* Remove the rest of interface checks: interface-is-not-class,
missing-interface-method, unresolved-interface. The reason is that
it's better to start recommending ABCs instead of the old Zope era
of interfaces. One side effect of this change is that ignore-iface-methods
becomes a noop, it's deprecated and it will be removed at some time.
* Emit a proper deprecation warning for reporters.BaseReporter.add_message.
The alternative way is to use handle_message. add_message will be removed in
Pylint 1.6.
* Added new module 'extensions' for optional checkers with the test
directory 'test/extensions' and documentation file 'doc/extensions.rst'.
* Added new checker 'extensions.check_docs' that verifies parameter
documentation in Sphinx, Google, and Numpy style.
* Detect undefined variable cases, where the "definition" of an undefined
variable was in del statement. Instead of emitting :ref:`used-before-assignment`,
which is totally misleading, it now emits :ref:`undefined-variable`.
Closes #528.
* Don't emit :ref:`attribute-defined-outside-init` and :ref:`access-member-before-definition`
for mixin classes. Actual errors can occur in mixin classes, but this is
controlled by the ignore-mixin-members option.
Closes #412.
* Improve the detection of undefined variables and variables used before
assignment for variables used as default arguments to function,
where the variable was first defined in the class scope.
Closes #342 and issue #404.
* Add a new warning, :ref:`unexpected-special-method-signature`, which is emitted
when a special method (dunder method) doesn't have the expected signature,
which can lead to actual errors in the application code.
Closes #253.
* Remove :ref:`bad-context-manager` due to the inclusion of :ref:`unexpected-special-method-signature`.
* Don't emit :ref:`no-name-in-module` if the import is guarded by an ImportError, Exception or
a bare except clause.
* Don't emit :ref:`no-member` if the attribute access node is protected by an
except handler, which handles AttributeError, Exception or it is a
bare except.
* Don't emit :ref:`import-error` if the import is guarded by an ImportError, Exception or a
bare except clause.
* Don't emit :ref:`undefined-variable` if the node is guarded by a NameError, Exception
or bare except clause.
* Add a new warning, :ref:`using-constant-test`, which is emitted when a conditional
statement (If, IfExp) uses a test which is always constant, such as numbers,
classes, functions etc. This is most likely an error from the user's part.
Closes #524.
* Don't emit :ref:`raising-non-exception` when the exception has unknown
bases. We don't know what those bases actually are and it's better
to assume that the user knows what he is doing rather than emitting
a message which can be considered a false positive.
* Look for a .pylintrc configuration file in the current folder,
if pylintrc is not found. Dotted pylintrc files will not be searched
in the parents of the current folder, as it is done for pylintrc.
* Add a new error, 'invalid-unary-type-operand', emitted when
an unary operand is used on something which doesn't support that
operation (for instance, using the unary bitwise inversion operator
on an instance which doesn't implement __invert__).
* Take in consideration differences between arguments of various
type of functions (classmethods, staticmethods, properties)
when checking for ``arguments-differ``.
Closes #548.
* astroid.inspector was moved to pylint.pyreverse, since it belongs
there and it doesn't need to be in astroid.
* astroid.utils.LocalsVisitor was moved to pylint.pyreverse.LocalsVisitor.
* pylint.checkers.utils.excepts_import_error was removed.
Use pylint.checkers.utils.error_of_type instead.
* Don't emit undefined-all-variables for nodes which can't be
inferred (YES nodes).
* yield-outside-func is also emitted for ``yield from``.
* Add a new error, :ref:`too-many-star-expressions`, emitted when
there are more than one starred expression (`*x`) in an assignment.
The warning is emitted only on Python 3.
* Add a new error, :ref:`invalid-star-assignment-target`, emitted when
a starred expression (`*x`) is used as the lhs side of an assignment,
as in `*x = [1, 2]`. This is not a SyntaxError on Python 3 though.
* Detect a couple of objects which can't be base classes (bool,
slice, range and memoryview, which weren't detected until now).
* Add a new error for the Python 3 porting checker, ``import-star-module-level``,
which is used when a star import is detected in another scope than the
module level, which is an error on Python 3. Using this will emit a
SyntaxWarning on Python 2.
* Add a new error, :ref:`star-needs-assignment-target`, emitted on Python 3 when
a Starred expression (`*x`) is not used in an assignment target. This is not
caught when parsing the AST on Python 3, so it needs to be a separate check.
* Add a new error, :ref:`unsupported-binary-operation`, emitted when
two a binary arithmetic operation is executed between two objects
which don't support it (a number plus a string for instance).
This is currently disabled, since the it exhibits way too many false
positives, but it will be re-enabled as soon as possible.
* New imported features from astroid into pyreverse: pyreverse.inspector.Project,
pyreverse.inspector.project_from_files and pyreverse.inspector.interfaces.
These were moved since they didn't belong in astroid.
* Enable :ref:`misplaced-future` for Python 3.
Closes #580.
* Add a new error, :ref:`nonlocal-and-global`, which is emitted when a
name is found to be both nonlocal and global in the same scope.
Closes #581.
* ignored-classes option can work with qualified names (ignored-classes=optparse.Values)
Closes #297
* ignored-modules can work with qualified names as well as with Unix pattern
matching for recursive ignoring.
Closes #244
* Improve detection of relative imports in non-packages, as well as importing
missing modules with a relative import from a package.
* Don't emit no-init if not all the bases from a class are known.
Closes #604.
* --no-space-check option accepts ``empty-line`` as a possible option.
Closes #541.
* --generate-rcfile generates by default human readable symbols
for the --disable option.
Closes #608.
* Improved the :ref:`not-in-loop` checker to properly detect more cases.
* Add a new error, :ref:`continue-in-finally`, which is emitted when
the ``continue`` keyword is found inside a ``finally`` clause, which
is a SyntaxError.
* The --zope flag is deprecated and it is slated for removal
in Pylint 1.6.
The reason behind this removal is the fact that it's a specialized
flag and there are solutions for the original problem:
use --generated-members with the members that causes problems
when using Zope or add AST transforms tailored to the zope
project.
At the same time, --include-ids and --symbols will also be removed
in Pylint 1.6.
Closes #570.
* missing-module-attribute was removed and the corresponding
CLI option, required-attributes, which is slated for removal
in Pylint 1.6.
* missing-reversed-argument was removed.
The reason behind this is that this kind of errors should be
detected by the type checker for *all* the builtins and not
as a special case for the reversed builtin. This will happen
shortly in the future.
* --comment flag is obsolete and it will be removed in Pylint 1.6.
* --profile flag is obsolete and it will be removed in Pylint 1.6.
* Add a new error, :ref:`misplaced-bare-raise`.
The error is used when a bare raise is not used inside an except clause.
This can generate a RuntimeError in Python, if there are no active exceptions
to be reraised. While it works in Python 2 due to the fact that the exception
leaks outside of the except block, it's nevertheless a behaviour that
a user shouldn't depend upon, since it's not obvious to the reader of the code
what exception will be raised and it will not be compatible with Python 3 anyhow.
Closes #633.
* Bring logilab-common's ureports into pylint.reporters.
With this change, we moved away from depending on logilab-common,
having in Pylint all the components that were used from logilab-common.
The API should be considered an implementation detail and can change at
some point in the future.
Closes #621.
* ``reimported`` is emitted for reimported objects on the same line.
Closes #639.
* Abbreviations of command line options are not supported anymore.
Using abbreviations for CLI options was never considered to be
a feature of pylint, this fact being only a side effect of using optparse.
As this was the case, using --load-plugin or other abbreviation
for --load-plugins never actually worked, while it also didn't raise
an error.
Closes #424.
* Add a new error, :ref:`nonlocal-without-binding`
The error is emitted on Python 3 when a nonlocal name is not bound
to any variable in the parents scopes.
Closes #582.
* :ref:`deprecated-module` can be shown for modules which aren't
available.
Closes #362.
* Don't consider a class abstract if its members can't
be properly inferred.
This fixes a false positive related to :ref:`abstract-class-instantiated`.
Closes #648.
* Add a new checker for the async features added by PEP 492.
* Add a new error, :ref:`yield-inside-async-function`, emitted on
Python 3.5 and upwards when the ``yield`` statement is found inside
a new coroutine function (PEP 492).
* Add a new error, :ref:`not-async-context-manager`, emitted when
an async context manager block is used with an object which doesn't
support this protocol (PEP 492).
* Add a new convention warning, :ref:`singleton-comparison`, emitted when
comparison to True, False or None is found.
* Don't emit :ref:`assigning-non-slot` for descriptors.
Closes #652.
* Add a new error, :ref:`repeated-keyword`, when a keyword argument is passed
multiple times into a function call.
This is similar with :ref:`redundant-keyword-arg`, but it's mildly different
that it needs to be a separate error.
* --enable=all can now be used.
Closes #142.
* Add a new convention message, :ref:`misplaced-comparison-constant`,
emitted when a constant is placed in the left hand side of a comparison,
as in '5 == func()'. This is also called Yoda condition, since the
flow of code reminds of the Star Wars green character, conditions usually
encountered in languages with variabile assignments in conditional
statements.
* Add a new convention message, :ref:`consider-using-enumerate`, which is
emitted when code that uses ``range`` and ``len`` for iterating is encountered.
Closes #684.
* Added two new refactoring messages, :ref:`no-classmethod-decorator` and
:ref:`no-staticmethod-decorator`, which are emitted when a static method or a class
method is declared without using decorators syntax.
Closes #675.
---
### Doc Whatsnew 1 Index (`doc/whatsnew/1/index.rst`)
1.x
===
.. include:: ../full_changelog_explanation.rst
.. include:: ../summary_explanation.rst
.. toctree::
:maxdepth: 2
1.9/index
1.8/index
1.7/index
1.6/index
Ticket numbers are almost can be internal to Logilab, or from bitbucket. In latest
version it's also github issues.
.. toctree::
:maxdepth: 2
1.5.rst
1.4.rst
1.3.rst
1.2.rst
1.1.rst
1.0.rst
---
### Doc Whatsnew 2 Index (`doc/whatsnew/2/index.rst`)
2.x
===
.. include:: ../full_changelog_explanation.rst
.. include:: ../summary_explanation.rst
.. toctree::
:maxdepth: 2
2.17/index
2.16/index
2.15/index
2.14/index
2.13/index
2.12/index
2.11/index
2.10/index
2.9/index
2.8/index
2.7/index
2.6/index
2.5/index
2.4/index
2.3/index
2.2/index
2.1/index
2.0/index
---
### Doc Whatsnew 3 Index (`doc/whatsnew/3/index.rst`)
3.x
===
This is the full list of change in pylint 3.x minors, by categories.
.. toctree::
:maxdepth: 2
3.3/index
3.2/index
3.1/index
3.0/index
---
### Doc Whatsnew 4 Index (`doc/whatsnew/4/index.rst`)
4.x
===
This is the full list of change in pylint 4.x minors, by categories.
.. toctree::
:maxdepth: 2
4.2/index
4.1/index
4.0/index
---
### Doc Whatsnew Fragments Template (`doc/whatsnew/fragments/_template.rst`)
{% set title = "What's new in Pylint " + versiondata.version + "?" %}
{{ title }}
{{ underlines[0] * (title|length) }}
Release date: {{ versiondata.date }}
{% for section, _ in sections.items() %}
{% set underline = underlines[0] %}{% if section %}{{section}}
{{ underline * section|length }}{% set underline = underlines[1] %}
{% endif %}
{% if sections[section] %}
{% for category, val in definitions.items() if category in sections[section]%}
{{ definitions[category]['name'] }}
{{ underline * definitions[category]['name']|length }}
{% if definitions[category]['showcontent'] %}
{% for text, values in sections[section][category].items() %}
- {{ text }} ({{ values|join(', ') }})
{% endfor %}
{% else %}
- {{ sections[section][category]['']|join(', ') }}
{% endif %}
{% if sections[section][category]|length == 0 %}
No significant changes.
{% else %}
{% endif %}
{% endfor %}
{% else %}
No significant changes.
{% endif %}
{% endfor %}
---
### Doc Development Guide Contributor Guide Tests Index (`doc/development_guide/contributor_guide/tests/index.rst`)
.. _contributor_testing:
.. _test_your_code:
==============
Testing pylint
==============
Pylint is very well tested and has a high code coverage. New contributions are not accepted
unless they include tests.
.. toctree::
:maxdepth: 3
:titlesonly:
install
launching_test
writing_test
---
### Doc Development Guide Contributor Guide Tests Install (`doc/development_guide/contributor_guide/tests/install.rst`)
.. _contributor_install:
Contributor installation
========================
Basic installation
------------------
Pylint is developed using the git_ distributed version control system.
You can clone Pylint using ::
git clone https://github.com/pylint-dev/pylint
Before you start testing your code, you need to install your source-code package locally.
Suppose you just cloned pylint with the previous ``git clone`` command. To set up your
environment for testing, open a terminal and run::
cd pylint
python3 -m venv venv
source venv/bin/activate
pip install -r requirements_test_min.txt
pip install -e .
This ensures your testing environment is similar to Pylint's testing environment on GitHub.
**Optionally** (Because there's an auto-fix if you open a merge request): We have
pre-commit hooks which should take care of the autoformatting for you before each
commit. To enable it, run ``pre-commit install`` in the ``pylint`` root directory.
Astroid installation
--------------------
If you're testing new changes in astroid you need to also clone astroid_ and install
with an editable installation alongside pylint as follows::
# Suppose you're in the pylint directory
git clone https://github.com/pylint-dev/astroid.git
python3 -m pip install -e astroid/
You're now using the local astroid in pylint and can control the version with git for example::
cd astroid/
git switch my-astroid-dev-branch
.. _pytest-cov: https://pypi.org/project/pytest-cov/
.. _astroid: https://github.com/pylint-dev/astroid
.. _git: https://git-scm.com/
---
### Doc Development Guide Contributor Guide Tests Launching Test (`doc/development_guide/contributor_guide/tests/launching_test.rst`)
Launching tests
===============
pytest
------
Since we use pytest_ to run the tests, you can also use it on its own.
We do recommend using the tox_ command though::
pytest tests/ -k test_functional
You can use pytest_ directly. If you want to run tests on a specific portion of the
code with pytest_ and your local python version::
python3 -m pytest
Everything in tests/message with coverage for the relevant code (require `pytest-cov`_)::
python3 -m pytest tests/message/ --cov=pylint.message
coverage html
Only the functional test "missing_kwoa_py3"::
python3 -m pytest "tests/test_functional.py::test_functional[missing_kwoa_py3]"
tox
---
You can also *optionally* install tox_ and run our tests using the tox_ package, as in::
python -m tox
python -m tox -epy313 # for Python 3.13 suite only
python -m tox -epylint # for running Pylint over Pylint's codebase
python -m tox -eformatting # for running formatting checks over Pylint's codebase
It's usually a good idea to run tox_ with ``--recreate``. This flag tells tox_ to re-download
all dependencies before running the tests. This can be important when a new version of
astroid_ or any of the other dependencies has been published::
python -m tox --recreate # The entire tox environment will be recreated
python -m tox --recreate -e py311 # The python 3.11 tox environment will be recreated
To run only a specific test suite, use a pattern for the test filename
(**without** the ``.py`` extension), as in::
python -m tox -e py310 -- -k test_functional
python -m tox -e py310 -- -k \*func\*
python -m tox --recreate -e py310 -- -k test_functional # With recreation of the environment
.. _primer_tests:
Primer tests
------------
Pylint uses what we refer to as ``primer`` tests. These run automatically
in our Continuous Integration and assess a pull request's impact by posting
the diff against ``main`` as a comment on the pull request. There are two
primers: the ``pylint`` primer, which checks for crashes on the ``stdlib``
and lints a selection of external repositories, and the ``pyreverse``
primer, which compares generated class diagrams for configured classes in
those repositories.
You can find the latest list of repositories and any relevant code for these tests in the ``tests/primer``
directory.
Pylint primer
~~~~~~~~~~~~~
To run the primer test for the ``stdlib``, which only checks for crashes and fatal errors, add
``--primer-stdlib`` to the pytest_ command::
pytest -m primer_stdlib --primer-stdlib
To produce the output generated on Continuous Integration for the linting of external repositories,
run these commands::
python tests/primer/__main__.py prepare --clone
python tests/primer/__main__.py run --type=pr
To fully simulate the process on Continuous Integration, checkout ``main`` and run::
python tests/primer/__main__.py run --type=main
python tests/primer/__main__.py compare --base-file=<main output> --new-file=<pr output> --commit=<sha>
The output files live in the ``tests/.pylint_primer_tests`` directory. On Continuous
Integration the run is split into several batches (see the ``--batches`` option).
The list of repositories is created on the basis of three criteria: 1) projects need to use a diverse
range of language features, 2) projects need to be well maintained and 3) projects should not have a codebase
that is too repetitive. This guarantees a good balance between speed of our CI and finding potential bugs.
Pyreverse primer
~~~~~~~~~~~~~~~~
The ``pyreverse`` primer tracks class diagrams instead of messages: for each configured
class it generates the diagram and posts the diff against ``main`` as a comment.
On Continuous Integration it runs on pull requests that touch ``pyreverse`` code
and carry the ``pyreverse`` label.
Tracked diagrams are declared with ``pyreverse_targets`` in
``tests/primer/packages_to_prime.json``. Each target names the class and the path
to run ``pyreverse`` on::
"classdef": {
"class_name": "astroid.nodes.scoped_nodes.scoped_nodes.ClassDef",
"path": "astroid"
}
To produce the output generated on Continuous Integration, run these commands::
python tests/primer/pyreverse_primer.py prepare --clone
python tests/primer/pyreverse_primer.py run --type=pr
To fully simulate the process on Continuous Integration, checkout ``main`` and run::
python tests/primer/pyreverse_primer.py run --type=main
python tests/primer/pyreverse_primer.py compare --base-file=<main output> --new-file= --commit=<sha>
The output files live in the ``tests/.pyreverse_primer_tests`` directory.
.. _pytest-cov: https://pypi.org/project/pytest-cov/
.. _astroid: https://github.com/pylint-dev/astroid
---
### Doc Development Guide Contributor Guide Tests Writing Test (`doc/development_guide/contributor_guide/tests/writing_test.rst`)
.. _writing_tests:
Writing tests
=============
Pylint uses three types of tests: unittests, functional tests and primer tests.
- :ref:`unittests <writing_unittests>` can be found in ``pylint/tests``. Unless you're working on pylint's
internal you're probably not going to have to write any.
- :ref:`Global functional tests <writing_functional_tests>` can be found in the ``pylint/tests/functional``. They are
mainly used to test whether Pylint emits the correct messages.
- :ref:`Configuration's functional tests <writing_config_functional_tests>` can be found in the
``pylint/tests/config/functional``. They are used to test Pylint's configuration loading.
- :ref:`Primer tests ` you can suggest a new external repository to check but there's nothing to do
most of the time.
.. _writing_unittests:
Unittest tests
--------------
Most other tests reside in the '/pylint/test' directory. These unittests can be used to test
almost all functionality within Pylint. A good step before writing any new unittests is to look
at some tests that test a similar functionality. This can often help write new tests.
If your new test requires any additional files you can put those in the
``/pylint/test/regrtest_data`` directory. This is the directory we use to store any data needed for
the unittests.
.. _writing_functional_tests:
Functional tests
----------------
These are located under ``/pylint/test/functional`` and they are formed of multiple
components. First, each Python file is considered to be a test case and it
should be accompanied by a ``.txt`` file, having the same name. The ``.txt`` file contains the ``pylint`` messages
that are supposed to be emitted by the given test file.
In your ``.py`` test file, each line for which Pylint is supposed to emit a message
has to be annotated with a comment following this pattern ``# [message_symbol]``, as in::
a, b, c = 1 # [unbalanced-tuple-unpacking]
If multiple messages are expected on the same line, then this syntax can be used::
a, b, c = 1.test # [unbalanced-tuple-unpacking, no-member]
You can also use ``# +n: [`` where ``n`` is an integer to deal with special cases, e.g., where the above regular syntax makes the line too long::
A = 5
# +1: [singleton-comparison]
B = A == None # The test will look for the `singleton-comparison` message in this line
If you need special control over Pylint's configuration, you can also create a ``.rc`` file, which
can set sections of Pylint's configuration.
The ``.rc`` file can also contain a section ``[testoptions]`` to pass options for the functional
test runner. The following options are currently supported:
- "min_pyver": Minimal python version required to run the test
- "max_pyver": Python version from which the test won't be run. If the last supported version is 3.9 this setting should be set to 3.10.
- "min_pyver_end_position": Minimal python version required to check the end_line and end_column attributes of the message
- "requires": Packages required to be installed locally to run the test
- "except_implementations": List of python implementations on which the test should not run
- "exclude_platforms": List of operating systems on which the test should not run
**Different output for different Python versions**
Sometimes the linting result can change between Python releases. In these cases errors can be marked as conditional.
Supported operators are ``<``, ``<=``, ``>`` and ``>=``.
.. code-block:: python
def some_func() -> X: # <3.14:[undefined-variable]
...
# It can also be combined with offsets
# +1:<3.14:[undefined-variable]
def some_other_func() -> X:
...
class X: ...
Since the output messages are different, it is necessary to add two separate files for it.
First ``<test-file-name>.314.txt``, this will include the output messages for ``>=3.14``, i.e. should be empty here.
Second ``<test-file-name>.txt``, this will be the default for all other Python versions.
.. note::
This does only work if the code itself is parsable in all tested Python versions.
For new syntax, use ``min_pyver`` / ``max_pyver`` instead.
**Functional test file locations**
For existing checkers, new test cases should preferably be appended to the existing test file.
For new checkers, a new file ``new_checker_message.py`` should be created (Note the use of
underscores). This file should then be placed in the ``test/functional/n`` sub-directory.
Some additional notes:
- If the checker is part of an extension the test should go in ``test/functional/ext/extension_name``
- If the test is a regression test it should go in ``test/r/regression`` or ``test/r/regression_02``.
The file name should start with ``regression_``.
- For some sub-directories, such as ``test/functional/u``, there are additional sub-directories (``test/functional/u/use``).
Please check if your test file should be placed in any of these directories. It should be placed there
if the sub-directory name matches the word before the first underscore of your test file name.
The folder structure is enforced when running the test suite, so you might be directed to put the file
in a different sub-directory.
**Running and updating functional tests**
During development, it's sometimes helpful to run all functional tests in your
current environment in order to have faster feedback. Run from Pylint root directory with::
python tests/test_functional.py
You can use all the options you would use for pytest_, for example ``-k "test_functional[len_checks]"``.
Furthermore, if required the .txt file with expected messages can be regenerated based
on the current output by appending ``--update-functional-output`` to the command line::
python tests/test_functional.py --update-functional-output -k "test_functional[len_checks]"
.. _writing_config_functional_tests:
Functional tests for configurations
-----------------------------------
To test the different ways to configure Pylint there is also a small functional test framework
for configuration files. These tests can be found in the '/pylint/test/config' directory.
To create a new test create a new file with an unused name in the directory of that type
of configuration file. Subsequently add a ``filename.result.json`` file with 'filename'
being the same name as your configuration file. This file should record
what the configuration should be **compared to the standard configuration**.
For example, if the configuration should add a warning to the list of disabled messages
and you changed the configuration for ``job`` to 10 instead of the default 1 the
``.json`` file should include::
"functional_append": {
"disable": [["a-message-to-be-added"],]
}
"jobs": 10,
Similarly if a message should be removed you can add the following to the ``.json`` file::
"functional_remove": {
"disable": [["a-message-to-be-removed"],]
}
If a configuration is incorrect and should lead to a crash or warning being emitted you can
specify this by adding a ``.out`` file. This file should have the following name
``name_of_configuration_testfile.error_code.out``. So, if your test is called ``bad_configuration.toml``
and should exit with exit code 2 the ``.out`` file should be named ``bad_configuration.2.out``.
The content of the ``.out`` file should have a similar pattern as a normal Pylint output. Note that the
module name should be ``{abspath}`` and the file name ``{relpath}``.
.. _tox: https://tox.wiki/en/latest/
.. _pytest: https://docs.pytest.org/en/latest/
.. _pytest-cov: https://pypi.org/project/pytest-cov/
.. _astroid: https://github.com/pylint-dev/astroid
---
### Doc User Guide Installation Ide Integration Flymake Emacs (`doc/user_guide/installation/ide_integration/flymake-emacs.rst`)
.. _pylint_in_flymake:
Using Pylint through Flymake in Emacs
=====================================
.. warning::
epylint was deprecated in 2.16.0 and targeted for deletion in 3.0.0.
All emacs and flymake related files were removed and their support will
now happen in an external repository: https://github.com/emacsorphanage/pylint.
---
### Doc User Guide Installation Ide Integration Index (`doc/user_guide/installation/ide_integration/index.rst`)
.. _ide-integration:
###########################
Editor and IDE integration
###########################
Pylint can be integrated in various editors and IDE's.
Below you can find tutorials for some of the most common ones.
- Eclipse_
- Emacs_
- `Eric IDE`_ in the `Project > Check` menu,
- gedit_ (`another option for gedit`_)
- :ref:`Flymake `
- `Jupyter Notebook`_
- Komodo_
- `Pycharm`_
- PyDev_
- pyscripter_ in the `Tool -> Tools` menu.
- Spyder_ in the `View -> Panes -> Static code analysis`
- `Sublime Text`_
- :ref:`TextMate `
- Vim_
- `Visual Studio Code`_ in the `Preferences -> Settings` menu
- `Visual Studio Code Pylint Extension`_
- `Visual Studio`_ in the `Python > Run PyLint` command on a project's context menu.
- WingIDE_
.. _Eclipse: https://www.pydev.org/manual_adv_pylint.html
.. _Emacs: https://www.emacswiki.org/emacs/PythonProgrammingInEmacs
.. _Eric IDE: https://eric-ide.python-projects.org/
.. _gedit: https://launchpad.net/gedit-pylint-2
.. _another option for gedit: https://wiki.gnome.org/Apps/Gedit/PylintPlugin
.. _Jupyter Notebook: https://github.com/nbQA-dev/nbQA
.. _Komodo: https://mateusz.loskot.net/post/2006/01/15/running-pylint-from-komodo/
.. _Pycharm: https://stackoverflow.com/a/46409649/2519059
.. _pydev: https://www.pydev.org/manual_adv_pylint.html
.. _pyscripter: https://github.com/pyscripter/pyscripter
.. _spyder: https://docs.spyder-ide.org/current/panes/pylint.html
.. _Sublime Text: https://packagecontrol.io/packages/SublimeLinter-pylint
.. _Vim: https://www.vim.org/scripts/script.php?script_id=891
.. _Visual Studio: https://docs.microsoft.com/visualstudio/python/code-pylint
.. _Visual Studio Code: https://code.visualstudio.com/docs/python/linting
.. _Visual Studio Code Pylint Extension: https://marketplace.visualstudio.com/items?itemName=ms-python.pylint
.. _WingIDE: https://wingware.com/doc/warnings/external-checkers
.. toctree::
:maxdepth: 2
:titlesonly:
:hidden:
flymake-emacs.rst
textmate.rst
---
### Doc User Guide Installation Ide Integration Textmate (`doc/user_guide/installation/ide_integration/textmate.rst`)
.. _pylint_in_textmate:
Integrate Pylint with TextMate
==============================
Install Pylint in the usual way::
pip install pylint
Install the `Python bundle for TextMate <https://github.com/textmate/python.tmbundle>`_:
#. select *TextMate* > *Preferences*
#. select the *Bundles* tab
#. find and tick the *Python* bundle in the list
You should now see it in *Bundles* > *Python*.
In *Preferences*, select the *Variables* tab. If a ``TM_PYCHECKER`` variable is not already listed, add
it, with the value ``pylint``.
The default keyboard shortcut to run the syntax checker is *Control-Shift-V* - open a ``.py`` file
in Textmate, and try it.
You should see the output in a new window:
PyCheckMate 1.2 โ Pylint 1.4.4
No config file found, using default configuration
Then all is well, and most likely Pylint will have expressed some opinions about your Python code
(or will exit with ``0`` if your code already conforms to its expectations).
If you receive a message:
Please install PyChecker, PyFlakes, Pylint, PEP 8 or flake8 for more extensive code checking.
That means that Pylint wasn't found, which is likely an issue with command paths - TextMate needs
be looking for Pylint on the right paths.
Check where Pylint has been installed, using ``which``::
$ which pylint
/usr/local/bin/pylint
The output will tell you where Pylint can be found; in this case, in ``/usr/local/bin``.
#. select *TextMate* > *Preferences*
#. select the *Variables* tab
#. find and check that a ``PATH`` variable exists, and that it contains the appropriate path (if
the path to Pylint were ``/usr/local/bin/pylint`` as above, then the variable would need to
contain ``/usr/local/bin``). An actual example in this case might be
``$PATH:/opt/local/bin:/usr/local/bin:/usr/texbin``, which includes other paths.
... and try running Pylint again.
---
### Doc Whatsnew 1 1.6 Full (`doc/whatsnew/1/1.6/full.rst`)
Full changelog
==============
What's new in Pylint 1.6.3?
----------------------------
Release date: 2016-07-18
* Do not crash when inferring uninferable exception types for docparams extension
Closes #998
What's new in Pylint 1.6.2?
----------------------------
Release date: 2016-07-15
* Do not crash when printing the help of options with default regular expressions
Closes #990
* More granular versions for deprecated modules.
Closes #991
What's new in Pylint 1.6.1?
----------------------------
Release date: 2016-07-07
* Use environment markers for supporting conditional dependencies.
What's New in Pylint 1.6.0?
---------------------------
Release date: 2016-07-03
* Added a new extension, ``pylint.extensions.mccabe``, for warning
about complexity in code.
* Deprecate support for --optimize-ast
Fixes part of #975
* Deprecate support for the HTML output
Fixes part of #975
* Deprecate support for --output-files
Fixes part of #975
* Fixed a documentation error for the check_docs extension.
Closes #735
* Made the list of property-defining decorators configurable.
* Fix a bug where the top name of a qualified import was detected as unused variable.
Closes #923
* :ref:`bad-builtin` is now an extension check.
* generated-members support qualified name through regular expressions.
For instance, one can specify a regular expression as --generated-members=astroid.node_classes.*
for ignoring every :ref:`no-member` error that is accessed as in ``astroid.node_classes.missing.object``.
* Add the ability to ignore files based on regex matching, with the new ``--ignore-patterns``
option. Allow for multiple ignore patterns to be specified. Rather than clobber the existing
ignore option, we introduced a new one called ignore-patterns.
Closes #156
* Added a new error, :ref:`trailing-newlines`, which is emitted when a file
has trailing new lines.
Closes #682
* Add a new option, 'redefining-builtins-modules', for controlling the modules
which can redefine builtins, such as six.moves and future.builtins.
Closes #464
* 'reimported' is emitted when the same name is imported from different module.
Closes #162
* Add a new recommendation checker, :ref:`consider-iterating-dictionary`, which is emitted
which is emitted when a dictionary is iterated through .keys().
Closes #699
* Use the configparser backport for Python 2
This fixes a problem we were having with comments inside values, which is fixed
in Python 3's configparser.
Closes #828
* A new error was added, :ref:`invalid-length-returned`, when the ``__len__``
special method returned something else than a non-negative number.
Closes #557
* Switch to using isort internally for :ref:`wrong-import-order`.
Closes #879
* check_docs extension can find constructor parameters in __init__.
Closes #887
* Don't warn about :ref:`invalid-sequence-index` if the indexed object has unknown base
classes.
Closes #867
* Don't crash when checking, for :ref:`super-init-not-called`, a method defined in an if block.
* Do not emit :ref:`import-error` or :ref:`no-name-in-module` for fallback import blocks by default.
Until now, we warned with these errors when a fallback import block (a TryExcept block
that contained imports for Python 2 and 3) was found, but this gets cumbersome when
trying to write compatible code. As such, we don't check these blocks by default,
but the analysis can be enforced by using the new ``--analyse-fallback-block`` flag.
Closes #769.
---
### Doc Whatsnew 1 1.6 Index (`doc/whatsnew/1/1.6/index.rst`)
**************************
What's New In Pylint 1.6
**************************
.. include:: ../../full_changelog_explanation.rst
.. include:: ../../summary_explanation.rst
Ticket numbers can be internal to logilab or come from bitbucket.
.. toctree::
:maxdepth: 2
summary.rst
full.rst
---
### Doc Whatsnew 1 1.6 Summary (`doc/whatsnew/1/1.6/summary.rst`)
:Release: 1.6.0
:Date: 2016-07-07
Summary -- Release highlights
=============================
Nothing major.
New checkers
============
* We added a new recommendation check, ``consider-iterating-dictionary``,
which is emitted when a dictionary is iterated by using ``.keys()``.
For instance, the following code would trigger this warning, since
the dictionary's keys can be iterated without calling the method explicitly.
.. code-block:: python
for key in dictionary.keys():
...
# Can be refactored to:
for key in dictionary:
...
* ``trailing-newlines`` check was added, which is emitted when a file has trailing newlines.
* ``invalid-length-returned`` check was added, which is emitted when the ``__len__``
special method returns something else than a non-negative number. For instance, this
example is triggering it::
class Container(object):
def __len__(self):
return self._items # Oups, forgot to call len() over it.
* Add a new check to the *check_docs* extension for looking for duplicate
constructor parameters in a class constructor docstring or in a class docstring.
The check ``multiple-constructor-doc`` is emitted when the parameter is documented
in both places.
* We added a new extension plugin, ``pylint.extensions.mccabe``, which can be used
for warning about the complexity in the code.
You can enable it as in::
$ pylint module_or_project --load-plugins=pylint.extensions.mccabe
See more at :ref:`pylint.extensions.mccabe`
New features
============
* ``generated-members`` now supports qualified names through regular expressions.
For instance, for ignoring all the errors generated by ``numpy.core``'s attributes, we can
now use::
$ pylint a.py --generated-members=numpy.*
* Add the ability to ignore files based on regex matching, with the new ``--ignore-patterns`` option.
Rather than clobber the existing ``ignore`` option, we decided to have a separate
option for it. For instance, for ignoring all the test files, we can now use::
$ pylint myproject --ignore-patterns=test.*?py
* We added a new option, ``redefining-builtins-modules``, which is used for
defining the modules which can redefine builtins.
*pylint* will emit an error when a builtin is redefined, such as defining
a variable called ``next``. But in some cases, the builtins can be
redefined in the case they are imported from other places, different
than the ``builtins`` module, such is the case for ``six.moves``, which
contains more forward-looking functions::
$ cat a.py
# Oups, now pylint emits a redefined-builtin message.
from six.moves import open
$ pylint a.py --redefining-builtins-modules=six.moves
Default values: ``six.moves,future.builtins``
Bug fixes
=========
* Fixed a bug where the top name of a qualified import was detected as an unused variable.
* We don't warn about ``invalid-sequence-index`` if the indexed object has unknown
base classes, that Pylint cannot deduce.
Other Changes
=============
* The ``bad-builtin`` check was moved into an extension.
The check was complaining about used builtin functions which
were supposed to not be used. For instance, ``map`` and ``filter``
were falling into this category, since better alternatives can
be used, such as list comprehensions. But the check was annoying,
since using ``map`` or ``filter`` can have its use cases and as
such, we decided to move it to an extension check instead.
It can now be enabled through ``--load-plugins=pylint.extensions.bad_builtin``.
* We use the ``configparser`` backport internally, for Python 2.
This allows having comments inside list values, in the configuration,
such as::
disable=no-member,
# Don't like this check
bad-indentation
* We now use the isort_ package internally.
This improves the ```wrong-import-order`` check, so now
we should have less false positives regarding the import order.
* We do not emit ``import-error`` or ``no-name-in-module`` for fallback import blocks by default.
A fallback import block can be considered a TryExcept block, which contains imports in both
branches, such as::
try:
import urllib.request as request
except ImportError:
import urllib2 as request
In the case where **pylint** can not find one import from the ``except`` branch, then
it will emit an ``import-error``, but this gets cumbersome when trying to write
compatible code for both Python versions. As such, we don't check these blocks by default,
but the analysis can be enforced by using the new ``--analyse-fallback-block`` flag.
* ``reimported`` is emitted when the same name is imported from different module, as in::
from collections import deque, OrderedDict, deque
Deprecated features
===================
* The HTML support was deprecated and will be eventually removed
in Pylint 1.7.0.
This feature was lately a second class citizen in Pylint, being
often neglected and having a couple of bugs. Since we now have
the JSON reporter, this can be used as a basis for more prettier
HTML outputs than what Pylint can currently offer.
* The ``--files-output`` option was deprecated and will be eventually
removed in Pylint 1.7.0.
* The ``--optimize-ast`` option was deprecated and will be eventually
removed in Pylint 1.7.0.
The option was initially added for handling pathological cases,
such as joining too many strings using the addition operator, which
was leading pylint to have a recursion error when trying to figure
out what the string was. Unfortunately, we decided to ignore the
issue, since the pathological case would have happen when the
code was parsed by Python as well, without actually reaching the
runtime step and as such, we will remove the option in the future.
* The ``check_docs`` extension is now deprecated. The extension is still available
under the ``docparams`` name, so this should work::
$ pylint module_or_package --load-extensions=pylint.extensions.docparams
The old name is still kept for backward compatibility, but it will be
eventually removed.
Removed features
================
* None yet
.. _isort: https://pypi.org/project/isort/
---
### Doc Whatsnew 1 1.7 Full (`doc/whatsnew/1/1.7/full.rst`)
Full changelog
==============
What's New in Pylint 1.7.1?
---------------------------
Release date: 2017-04-17
* Fix a false positive which occurred when an exception was reraised
Closes #1419
* Fix a false positive of ``disallow-trailing-tuple``
The check was improved by verifying for non-terminating newlines, which
should exempt function calls and function definitions from the check
Closes #1424
What's New in Pylint 1.7?
-------------------------
Release date: 2017-04-13
* Don't emit :ref:`missing-final-newline` or :ref:`trailing-whitespace` for formfeeds (page breaks).
Closes #1218 and #1219
* Don't emit by default :ref:`no-member` if we have opaque inference objects in the inference results
This is controlled through the new flag ignore-on-opaque-inference, which is by
default True. The inference can return multiple potential results while
evaluating a Python object, but some branches might not be evaluated, which
results in partial inference. In that case, it might be useful to still emit
:ref:`no-member` and other checks for the rest of the inferred objects.
* Added new message ``assign-to-new-keyword`` to warn about assigning to names which
will become a keyword in future Python releases.
Closes #1351
* Split the 'missing or differing' in parameter documentation in different error.
:ref:`differing-param-doc` covers the differing part of the old :ref:`missing-param-doc`',
and :ref:`differing-type-doc`' covers the differing part of the old :ref:`missing-type-doc`'
Closes #1342
* Added a new error, :ref:`used-prior-global-declaration`', which is emitted when a name
is used prior a global declaration in a function. This causes a SyntaxError in
Python 3.6
Closes #1257
* The protocol checks are emitting their messages when a special method is set to None.
Closes #1263
* Properly detect if imported name is assigned to same name in different
scope.
Closes #636, #848, #851, and #900
* Require one space for annotations with type hints, as per PEP 8.
* :ref:`trailing-comma-tuple`' check was added
This message is emitted when pylint finds an one-element tuple,
created by a stray comma. This can suggest a potential problem in the
code and it is recommended to use parentheses in order to emphasise the
creation of a tuple, rather than relying on the comma itself.
* Don't emit :ref:`not-callable` for instances with unknown bases.
Closes #1213
* Treat keyword only arguments the same as positional arguments with regard to :ref:`unused-argument` check
* Don't try to access variables defined in a separate scope when checking for ``protected-access``
* Added new check to detect incorrect usage of len(SEQUENCE) inside
test conditions.
* Added new extension to detect comparisons against empty string constants
* Added new extension to detect comparisons of integers against zero
* Added new error conditions for :ref:`bad-super-call`'
Now detects ``super(type(self), self)`` and ``super(self.__class__, self)``
which can lead to recursion loop in derived classes.
* PyLinter.should_analyze_file has a new optional parameter, called ``is_argument``
Closes #1079
* Add attribute hints for missing members
Closes #1035
* Add a new warning, :ref:`redefined-argument-from-local`'
Closes #649
* Support inline comments for comma separated values in the config file
Closes #1024
* epylint.py_run's *script* parameter was removed.
* epylint.py_run now uses ``shell=False`` for running the underlying process.
Closes #441
* Added a new warning, :ref:`useless-super-delegation`'
Close 839.
* Added a new error, :ref:`invalid-metaclass`', raised when
we can detect that a class is using an improper metaclass.
Closes #579
* Added a new refactoring message, :ref:`literal-comparison`'.
Closes #786
* :ref:`arguments-differ` takes in consideration kwonlyargs and variadics
Closes #983
* Removed --optimized-ast
Fixes part of #975
* Removed --files-output option
Fixes part of #975
* Removed pylint-gui from the package.
* Removed the HTML reporter
Fixes part of #975
* ignored-argument-names is now used for ignoring arguments for :ref:`unused-variable` check.
This option was used for ignoring arguments when computing the correct number of arguments
a function should have, but for handling the arguments with regard
to :ref:`unused-variable` check, dummy-variables-rgx was used instead. Now, ignored-argument-names
is used for its original purpose and also for ignoring the matched arguments for
the :ref:`unused-variable` check. This offers a better control of what should be ignored
and how.
Also, the same option was moved from the design checker to the variables checker,
which means that the option now appears under the ``[VARIABLES]`` section inside
the configuration file.
Closes #862.
* Fix a false positive for keyword variadics with regard to keyword only arguments.
If a keyword only argument was necessary for a function, but that function was called
with keyword variadics (\**kwargs), then we were emitting a :ref:`missing-kwoa` false positive,
which is now fixed.
Closes #934.
* Fix some false positives with unknown sized variadics.
Closes #878
* Added a new extension, check_docstring, for checking PEP 257 conventions.
Closes #868.
* config files with BOM markers can now be read.
Closes #864.
* epylint.py_run does not crash on big files, using .communicate() instead of .wait()
Closes #599
* Disable reports by default and show the evaluation score by default
The reports were disabled by default in order to simplify the interaction
between the tool and the users. The score is still shown by default, as
a way of closely measuring when it increases or decreases due to changes
brought to the code.
Refs #746
* Disable the information category messages by default. This is a step towards
making pylint more sane.
Refs #746.
* Catch more cases as not proper iterables for __slots__ with
regard to :ref:`invalid-slots` pattern.
Closes #775
* empty indent strings are rejected.
* Added a new error, :ref:`relative-beyond-top-level`', which is emitted
when a relative import was attempted beyond the top level package.
Closes #588
* Added a new warning, :ref:`unsupported-assignment-operation`', which is
emitted when item assignment is tried on an object which doesn't
have this ability.
Closes #591
* Added a new warning, :ref:`unsupported-delete-operation`', which is
emitted when item deletion is tried on an object which doesn't
have this ability.
Closes #592
* Fix a false positive of :ref:`redundant-returns-doc`', occurred when the documented
function was using *yield* instead of *return*.
Closes #984.
* Fix false positives of 'missing-[raises|params|type]-doc' due to not
recognizing keyword synonyms supported by Sphinx.
* Added a new refactoring message, :ref:`consider-merging-isinstance`', which is
emitted whenever we can detect that consecutive isinstance calls can be
merged together.
Closes #968
* Fix a false positive of :ref:`missing-param-doc`' and :ref:`missing-type-doc`',
occurred when a class docstring uses the 'For the parameters, see'
magic string but the class __init__ docstring does not, or vice versa.
* ``redefined-outer-name`` is now also emitted when a nested loop's target
variable is the same as a target variable in an outer loop.
Closes #911.
* Added proper exception type inference for :ref:`missing-raises-doc`'.
* Added InvalidMessageError exception class to replace asserts in
pylint.utils.
* More thorough validation in MessagesStore.register_messages() to avoid
one message accidentally overwriting another.
* InvalidMessageError, UnknownMessage, and EmptyReport exceptions are
moved to the new pylint.exceptions submodule.
* UnknownMessage and EmptyReport are renamed to UnknownMessageError and
EmptyReportError.
* Warnings 'missing-returns-type-doc' and 'missing-yields-type-doc'
have each been split into two warnings - 'missing-[return|yield]-doc'
and 'missing-[return|yield]-type-doc'.
* Added epytext support to docparams extension.
Closes #1029
* Support having plugins with the same name and with options defined
Closes #1018
* Sort configuration options in a section
Closes #1087
* Added a new Python 3 warning around implementing '__div__', '__idiv__', or
'__rdiv__' as those methods are phased out in Python 3.
* Added a new warning, :ref:`overlapping-except`', which is
emitted when two exceptions in the same except-clause are aliases
for each other or one exceptions is an ancestor of another.
* Avoid crashing on ill-formatted strings when checking for string formatting errors.
* Added a new Python 3 warning for calling 'str.encode' or 'str.decode' with a non-text
encoding.
* Added new coding convention message, :ref:`single-string-used-for-slots`'.
Closes #1166
* Added a new Python 3 check for accessing 'sys.maxint' which was removed in Python 3 in favor
of 'sys.maxsize'
* Added a new Python 3 check for bad imports.
* Added a new Python 3 check for accessing deprecated string functions.
* Do not warn about unused arguments or function being redefined in singledispatch
registered implementations.
Closes #1032 and #1034
* Added refactoring message :ref:`no-else-return`'.
* Improve :ref:`unused-variable` checker to warn about unused variables in module scope.
Closes #919
* Ignore modules import as _ when checking for unused imports.
Closes #1190
* Improve handing of Python 3 classes with metaclasses declared in nested scopes.
Closes #1177
* Added refactoring message :ref:`consider-using-ternary`'.
Closes #1204
* Bug-fix for false-positive logging-format-interpolation` when format specifications
are used in formatted string.
Closes #572
* Added a new switch ``single-line-class-stmt`` to allow single-line declaration
of empty class bodies.
Closes #738
* Protected access in form ``type(self)._attribute`` are now allowed.
Closes #1031
* Let the user modify msg-template when Pylint is called from a Python script
Closes #1269
* Imports checker supports new switch ``allow-wildcard-with-all`` which disables
warning on wildcard import when imported module defines ``__all__`` variable.
Closes #831
* ``too-many-format-args`` and ``too-few-format-args`` are emitted correctly when
starred expression are used in RHS tuple.
Closes #957
* ``cyclic-import`` checker supports local disable clauses. When one
of cycle imports was done in scope where disable clause was active,
cycle is not reported as violation.
Closes #59
---
### Doc Whatsnew 1 1.7 Index (`doc/whatsnew/1/1.7/index.rst`)
**************************
What's New In Pylint 1.7
**************************
.. include:: ../../full_changelog_explanation.rst
.. include:: ../../summary_explanation.rst
.. toctree::
:maxdepth: 2
summary.rst
full.rst
---
### Doc Whatsnew 1 1.7 Summary (`doc/whatsnew/1/1.7/summary.rst`)
:Release: 1.7
:Date: 2017-04-13
Summary -- Release highlights
=============================
New checkers
============
* ``single-string-used-for-slots`` check was added, which is used
whenever a class is using a single string as a slot value. While this
is technically not a problem per se, it might trip users when manipulating
the slots value as an iterable, which would in turn iterate over characters
of the slot value. In order to be more straight-forward, always try to use
a container such as a list or a tuple for defining slot values.
* We added a new check, ``literal-comparison``, which is used
whenever **pylint** can detect a comparison to a literal. This is usually
not what we want and, potentially, error prone. For instance, in the given example,
the first string comparison returns true, since smaller strings are interned
by the interpreter, while for larger ones, it will return False:
.. rstcheck: ignore-next-code-block
.. code-block:: python
mystring = "ok"
if mystring is "ok": # Returns true
...
mystring = "a" * 1000
if mystring is ("a" * 1000): # This will return False
...
Instead of using the ``is`` operator, you should use the ``==`` operator for
this use case.
* We added a new refactoring message, ``consider-merging-isinstance``, which is
emitted whenever we can detect that consecutive *isinstance* calls can be merged
together.
For instance, in this example, we can merge the first two *isinstance* calls:
.. code-block:: python
# $ cat a.py
if isinstance(x, int) or isinstance(x, float):
pass
if isinstance(x, (int, float)) or isinstance(x, str):
pass
# $ pylint a.py
# R: 1, 0: Consider merging these isinstance calls to isinstance(x, (float, int)) (consider-merging-isinstance)
# R: 3, 0: Consider merging these isinstance calls to isinstance(x, (int, float, str)) (consider-merging-isinstance)
* A new error check was added, ``invalid-metaclass``, which is used whenever *pylint*
can detect that a given class is using a metaclass which is invalid for the purpose
of the class. This usually might indicate a problem in the code, rather than
something done on purpose.
.. code-block:: python
# Needs to inherit from *type* in order to be valid
class SomeClass(object):
...
class MyClass(metaclass=SomeClass):
pass
* A new warning was added, ``useless-super-delegation``, which is used whenever
we can detect that an overridden method is useless, relying on *super()* delegation
to do the same thing as another method from the MRO.
For instance, in this example, the first two methods are useless, since they
do the exact same thing as the methods from the base classes, while the next
two methods are not, since they do some extra operations with the passed
arguments.
.. code-block:: python
class Impl(Base):
def __init__(self, param1, param2):
super(Impl, self).__init__(param1, param2)
def useless(self, first, second):
return super(Impl, self).useless(first, second)
def not_useless(self, first, **kwargs):
debug = kwargs.pop('debug', False)
if debug:
...
return super(Impl, self).not_useless(first, **kwargs)
def not_useless_1(self, first, *args):
return super(Impl, self).not_useless_1(first + some_value, *args)
* A new warning was added, ``len-as-condition``, which is used whenever
we detect that a condition uses ``len(SEQUENCE)`` incorrectly. Instead
one could use ``if SEQUENCE`` or ``if not SEQUENCE``.
For instance, all of the examples below:
.. code-block:: python
if len(S):
pass
if not len(S):
pass
if len(S) > 0:
pass
if len(S) != 0:
pass
if len(S) == 0:
pass
can be written in a more natural way:
.. code-block:: python
if S:
pass
if not S:
pass
See https://peps.python.org/pep-0008/#programming-recommendations
for more information.
* A new extension was added, ``emptystring.py`` which detects whenever
we detect comparisons to empty string constants. This extension is disabled
by default. For instance, the examples below:
.. code-block:: python
if S != "":
pass
if S == '':
pass
can be written in a more natural way:
.. code-block:: python
if S:
pass
if not S:
pass
An exception to this is when empty string is an allowed value whose meaning
is treated differently than ``None``. For example the meaning could be
user selected no additional options vs. user has not made their selection yet!
You can activate this checker by adding the line::
load-plugins=pylint.extensions.emptystring
to the ``MAIN`` section of your ``.pylintrc`` or using the command::
$ pylint a.py --load-plugins=pylint.extensions.emptystring
* A new extension was added, ``comparetozero.py`` which detects whenever
we compare integers to zero. This extension is disabled by default.
For instance, the examples below:
.. code-block:: python
if X != 0:
pass
if X == 0:
pass
can be written in a more natural way:
.. code-block:: python
if X:
pass
if not X:
pass
An exception to this is when zero is an allowed value whose meaning
is treated differently than ``None``. For example the meaning could be
``None`` means no limit, while ``0`` means the limit it zero!
You can activate this checker by adding the line::
load-plugins=pylint.extensions.comparetozero
to the ``MAIN`` section of your ``.pylintrc`` or using the command::
$ pylint a.py --load-plugins=pylint.extensions.comparetozero
* We've added new error conditions for ``bad-super-call`` which now detect
the usage of ``super(type(self), self)`` and ``super(self.__class__, self)``
patterns. These can lead to recursion loop in derived classes. The problem
is visible only if you override a class that uses these incorrect invocations
of ``super()``.
For instance, ``Derived.__init__()`` will correctly call ``Base.__init__``.
At this point ``type(self)`` will be equal to ``Derived`` and the call again
goes to ``Base.__init__`` and we enter a recursion loop.
.. code-block:: python
class Base(object):
def __init__(self, param1, param2):
super(type(self), self).__init__(param1, param2)
class Derived(Base):
def __init__(self, param1, param2):
super(Derived, self).__init__(param1, param2)
* The warnings ``missing-returns-doc`` and ``missing-yields-doc`` have each
been replaced with two new warnings - ``missing-[return|yield]-doc`` and
``missing-[return|yield]-type-doc``. Having these as separate warnings
allows the user to choose whether their documentation style requires
text descriptions of function return/yield, specification of return/yield
types, or both.
.. code-block:: python
# This will raise missing-return-type-doc but not missing-return-doc
def my_sphinx_style_func(self):
"""This is a Sphinx-style docstring.
:returns: Always False
"""
return False
# This will raise missing-return-doc but not missing-return-type-doc
def my_google_style_func(self):
"""This is a Google-style docstring.
Returns:
bool:
"""
return False
* A new refactoring check was added, ``redefined-argument-from-local``, which is
emitted when **pylint** can detect than a function argument is redefined locally
in some potential error prone cases. For instance, in the following piece of code,
we have a bug, since the check will never return ``True``, given the fact that we
are comparing the same object to its attributes.
.. code-block:: python
def test(resource):
for resource in resources:
# The ``for`` is reusing ``resource``, which means that the following
# ``resource`` is not what we wanted to check against.
if resource.resource_type == resource:
call_resource(resource)
Other places where this check looks are *with* statement name bindings and
except handler's name binding.
* A new refactoring check was added, ``no-else-return``, which is
emitted when pylint encounters an else following a chain of ifs,
all of them containing a return statement.
.. code-block:: python
def foo1(x, y, z):
if x:
return y
else: # This is unnecessary here.
return z
We could fix it deleting the ``else`` statement.
.. code-block:: python
def foo1(x, y, z):
if x:
return y
return z
* A new Python 3 check was added, ``eq-without-hash``, which enforces classes that implement
``__eq__`` *also* implement ``__hash__``. The behavior around classes which implement ``__eq__``
but not ``__hash__`` changed in Python 3; in Python 2 such classes would get ``object.__hash__``
as their default implementation. In Python 3, aforementioned classes get ``None`` as their
implementation thus making them unhashable.
.. code-block:: python
class JustEq(object):
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
class Neither(object):
def __init__(self, x):
self.x = x
class HashAndEq(object):
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
def __hash__(self):
return hash(self.x)
{Neither(1), Neither(2)} # OK in Python 2 and Python 3
{HashAndEq(1), HashAndEq(2)} # OK in Python 2 and Python 3
{JustEq(1), JustEq(2)} # Works in Python 2, throws in Python 3
In general, this is a poor practice which motivated the behavior change.
.. code-block:: python
as_set = {JustEq(1), JustEq(2)}
print(JustEq(1) in as_set) # prints False
print(JustEq(1) in list(as_set)) # prints True
In order to fix this error and avoid behavior differences between Python 2 and Python 3, classes
should either explicitly set ``__hash__`` to ``None`` or implement a hashing function.
.. code-block:: python
class JustEq(object):
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
__hash__ = None
{JustEq(1), JustEq(2)} # Now throws an exception in both Python 2 and Python 3.
* 3 new Python 3 checkers were added, ``div-method``, ``idiv-method`` and ``rdiv-method``.
The magic methods ``__div__`` and ``__idiv__`` have been phased out in Python 3 in favor
of ``__truediv__``. Classes implementing ``__div__`` that still need to be used from Python
2 code not using ``from __future__ import division`` should implement ``__truediv__`` and
alias ``__div__`` to that implementation.
.. code-block:: python
from __future__ import division
class DivisibleThing(object):
def __init__(self, x):
self.x = x
def __truediv__(self, other):
return DivisibleThing(self.x / other.x)
__div__ = __truediv__
* A new Python 3 checker was added to warn about accessing the ``message`` attribute on
Exceptions. The message attribute was deprecated in Python 2.7 and was removed in Python 3.
See https://peps.python.org/pep-0352/#retracted-ideas for more information.
.. code-block:: python
try:
raise Exception("Oh No!!")
except Exception as e:
print(e.message)
Instead of relying on the ``message`` attribute, you should explicitly cast the exception to a
string:
.. code-block:: python
try:
raise Exception("Oh No!!")
except Exception as e:
print(str(e))
* A new Python 3 checker was added to warn about using ``encode`` or ``decode`` on strings
with non-text codecs. This check also checks calls to ``open`` with the keyword argument
``encoding``. See https://docs.python.org/3/whatsnew/3.4.html#improvements-to-codec-handling
for more information.
.. code-block:: python
'hello world'.encode('hex')
Instead of using the ``encode`` method for non-text codecs use the ``codecs`` module.
.. code-block:: python
import codecs
codecs.encode('hello world', 'hex')
* A new warning was added, ``overlapping-except``, which is emitted
when an except handler treats two exceptions which are *overlapping*.
This means that one exception is an ancestor of the other one or it is
just an alias.
For example, in Python 3.3+, IOError is an alias for OSError. In addition, socket.error is
an alias for OSError. The intention is to find cases like the following:
.. code-block:: python
import socket
try:
pass
except (ConnectionError, IOError, OSError, socket.error):
pass
* A new Python 3 checker was added to warn about accessing ``sys.maxint``. This attribute was
removed in Python 3 in favor of ``sys.maxsize``.
.. code-block:: python
import sys
print(sys.maxint)
Instead of using ``sys.maxint``, use ``sys.maxsize``
.. code-block:: python
import sys
print(sys.maxsize)
* A new Python 3 checker was added to warn about importing modules that have either moved or been
removed from the standard library.
One of the major undertakings with Python 3 was a reorganization of the standard library to
remove old or supplanted modules and reorganize some of the existing modules. As a result,
roughly 100 modules that exist in Python 2 no longer exist in Python 3. See
https://peps.python.org/pep-3108/ and https://peps.python.org/pep-0004/ for more
information. There were suggestions on how to handle this, at
pythonhosted.org/six/#module-six.moves (dead link) or python3porting.com/stdlib.html (dead link).
.. code-block:: python
from cStringIO import StringIO
Instead of directly importing the deprecated module, either use ``six.moves`` or a conditional
import.
.. code-block:: python
from six.moves import cStringIO as StringIO
if sys.version_info[0] >= 3:
from io import StringIO
else:
from cStringIO import StringIO
This checker will assume any imports that happen within a conditional or a ``try/except`` block
are valid.
* A new Python 3 checker was added to warn about accessing deprecated functions on the string
module. Python 3 removed functions that were duplicated from the builtin ``str`` class. See
https://docs.python.org/2/library/string.html#deprecated-string-functions for more information.
.. code-block:: python
import string
print(string.upper('hello world!'))
Instead of using ``string.upper``, call the ``upper`` method directly on the string object.
.. code-block:: python
"hello world!".upper()
* A new Python 3 checker was added to warn about calling ``str.translate`` with the removed
``deletechars`` parameter. ``str.translate`` is frequently used as a way to remove characters
from a string.
.. code-block:: python
'hello world'.translate(None, 'low')
Unfortunately, there is not an idiomatic way of writing this call in a 2and3 compatible way. If
this code is not in the critical path for your application and the use of ``translate`` was a
premature optimization, consider using ``re.sub`` instead:
.. code-block:: python
import re
chars_to_remove = re.compile('[low]')
chars_to_remove.sub('', 'hello world')
If this code is in your critical path and must be as fast as possible, consider declaring a
helper method that varies based upon Python version.
.. code-block:: python
if six.PY3:
def _remove_characters(text, deletechars):
return text.translate({ord(x): None for x in deletechars})
else:
def _remove_characters(text, deletechars):
return text.translate(None, deletechars)
* A new refactoring check was added, ``consider-using-ternary``, which is
emitted when pylint encounters constructs which were used to emulate
ternary statement before it was introduced in Python 2.5.
.. code-block:: python
value = condition and truth_value or false_value
Warning can be fixed by using standard ternary construct:
.. code-block:: python
value = truth_value if condition else false_value
* A new refactoring check was added, ``trailing-comma-tuple``, which is emitted
when pylint finds an one-element tuple, created by a stray comma. This can
suggest a potential problem in the code and it is recommended to use parentheses
in order to emphasise the creation of a tuple, rather than relying on the comma
itself.
The warning is emitted for such a construct:
.. code-block:: python
a = 1,
The warning can be fixed by adding parentheses:
.. code-block:: python
a = (1, )
* Two new check were added for detecting an unsupported operation
over an instance, ``unsupported-assignment-operation`` and ``unsupported-delete-operation``.
The first one is emitted whenever an object does not support item assignment, while
the second is emitted when an object does not support item deletion:
.. code-block:: python
class A:
pass
instance = A()
instance[4] = 4 # unsupported-assignment-operation
del instance[4] # unsupported-delete-operation
* A new check was added, ``relative-beyond-top-level``, which is emitted
when a relative import tries to access too many levels in the current package.
* A new check was added, ``trailing-newlines``, which is emitted when a file
has trailing new lines.
* ``invalid-length-returned`` check was added, which is emitted when a ``__len__``
implementation does not return a non-negative integer.
* There is a new extension, ``pylint.extensions.mccabe``, which can be used for
computing the McCabe complexity of classes and functions.
You can enable this extension through ``--load-plugins=pylint.extensions.mccabe``
* A new check was added, ``used-prior-global-declaration``. This is emitted when
a name is used prior a global declaration, resulting in a SyntaxError in Python 3.6.
* A new message was added, ``assign-to-new-keyword``. This is emitted when used name
is known to become a keyword in future Python release. Assignments to keywords
would result in ``SyntaxError`` after switching to newer interpreter version.
.. rstcheck: ignore-next-code-block
.. code-block:: python
# While it's correct in Python 2.x, it raises a SyntaxError in Python 3.x
True = 1
False = 0
# Same as above, but it'll be a SyntaxError starting from Python 3.7
async = "async"
await = "await"
Other Changes
=============
* We don't emit by default ``no-member`` if we have opaque inference objects in the inference results
This is controlled through the new flag ``--ignore-on-opaque-inference``, which is by
default True. The inference can return multiple potential results while
evaluating a Python object, but some branches might not be evaluated, which
results in partial inference. In that case, it might be useful to still emit
:ref:`no-member` and other checks for the rest of the inferred objects.
* Namespace packages are now supported by pylint. This includes both explicit namespace
packages and implicit namespace packages, supported in Python 3 through PEP 420.
* A new option was added, ``--analyse-fallback-block``.
This can be used to support both Python 2 and 3 compatible import block code,
which means that the import block might have code that exists only in one or another
interpreter, leading to false positives when analysed. By default, this is false, you
can enable the analysis for both branches using this flag.
* ``ignored-argument-names`` option is now used for ignoring arguments
for :ref:`unused-variable` check.
This option was used for ignoring arguments when computing the correct number of arguments
a function should have, but for handling the arguments with regard
to :ref:`unused-variable` check, dummy-variables-rgx was used instead. Now, ignored-argument-names
is used for its original purpose and also for ignoring the matched arguments for
the :ref:`unused-variable` check. This offers a better control of what should be ignored
and how.
Also, the same option was moved from the design checker to the variables checker,
which means that the option now appears under the ``[VARIABLES]`` section inside
the configuration file.
* A new option was added, ``redefining-builtins-modules``, for controlling the modules
which can redefine builtins, such as six.moves and future.builtins.
* A new option was added, ``ignore-patterns``, which is used for building a
ignore list of directories and files matching the regex patterns, similar to the
``ignore`` option.
* The reports are now disabled by default, as well as the information category
warnings.
* ``arguments-differ`` check was rewritten to take in consideration
keyword only parameters and variadics.
Now it also complains about losing or adding capabilities to a method,
by introducing positional or keyword variadics. For instance, *pylint*
now complains about these cases:
.. code-block:: python
class Parent(object):
def foo(self, first, second):
...
def bar(self, **kwargs):
...
def baz(self, *, first):
...
class Child(Parent):
# Why subclassing in the first place?
def foo(self, *args, **kwargs):
# mutate args or kwargs.
super(Child, self).foo(*args, **kwargs)
def bar(self, first=None, second=None, **kwargs):
...
# The overridden method adds two new parameters,
# which can also be passed as positional arguments,
# breaking the contract of the parent's method.
def baz(self, first):
...
# Not keyword-only
* ``redefined-outer-name`` is now also emitted when a
nested loop's target variable is the same as an outer loop.
.. code-block:: python
for i, j in [(1, 2), (3, 4)]:
for j in range(i):
print(j)
* relax character limit for method and function names that starts with ``_``.
This will let people to use longer descriptive names for methods and
functions with a shorter scope (considered as private). The same idea
applies to variable names, only with an inverse rule: you want long
descriptive names for variables with bigger scope, like globals.
* Add ``InvalidMessageError`` exception class and replace ``assert`` in
pylint.utils with ``raise InvalidMessageError``.
* ``UnknownMessageError`` (formerly ``UnknownMessage``) and
``EmptyReportError`` (formerly ``EmptyReport``) are now provided by the new
``pylint.exceptions`` submodule instead of ``pylint.utils`` as before.
* We now support inline comments for comma separated values in the configurations
For instance, you can now use the **#** sign for having comments inside
comma separated values, as seen below::
disable=no-member, # Don't care about it for now
bad-indentation, # No need for this
import-error
Of course, interweaving comments with values is also working::
disable=no-member,
# Don't care about it for now
bad-indentation # No need for this
This works by setting the `inline comment prefixes`_ accordingly.
* Added epytext docstring support to the docparams extension.
* We added support for providing hints when not finding a missing member.
For example, given the following code, it should be obvious that
the programmer intended to use the ``mail`` attribute, rather than
``email``.
.. code-block:: python
class Contribution:
def __init__(self, name, email, date):
self.name = name
self.mail = mail
self.date = date
for c in contributions:
print(c.email) # Oups
**pylint** will now warn that there is a chance of having a typo,
suggesting new names that could be used instead.
.. code-block:: sh
$ pylint a.py
E: 8,10: Instance of 'Contribution' has no 'email' member; maybe 'mail'?
The behaviour is controlled through the ``--missing-member-hint`` option.
Other options that come with this change are ``--missing-member-max-choices``
for choosing the total number of choices that should be picked in this
situation and ``--missing-member-hint-distance``, which specifies a metric
for computing the distance between the names (this is based on Levenshtein
distance, which means the lower the number, the more pickier the algorithm
will be).
* ``PyLinter.should_analyze_file`` has a new parameter, ``is_argument``,
which specifies if the given path is a **pylint** argument or not.
``should_analyze_file`` is called whenever **pylint** tries to determine
if a file should be analyzed, defaulting to files with the ``.py``
extension, but this function gets called only in the case where the said
file is not passed as a command line argument to **pylint**. This usually
means that pylint will analyze a file, even if that file has a different
extension, as long as the file was explicitly passed at command line.
Since ``should_analyze_file`` cannot be overridden to handle all the cases,
the check for the provenience of files was moved into ``should_analyze_file``.
This means we now can write something similar with this example, for ignoring
every file respecting the desired property, disregarding the provenience of the
file, being it a file passed as CLI argument or part of a package.
.. code-block:: python
from pylint.lint import Run, PyLinter
class CustomPyLinter(PyLinter):
def should_analyze_file(self, modname, path, is_argument=False):
if respect_condition(path):
return False
return super().should_analyze_file(modname, path, is_argument=is_argument)
class CustomRun(Run):
LinterClass = CustomPyLinter
CustomRun(sys.argv[1:])
* Imports aliased with underscore are skipped when checking for unused imports.
* ``bad-builtin`` and ``redefined-variable-type`` are now extensions,
being disabled by default. They can be enabled through:
``--load-plugins=pylint.extensions.redefined_variable_type,pylint.extensions.bad_builtin``
* Imports checker supports new switch ``allow-wildcard-with-all`` which disables
warning on wildcard import when imported module defines ``__all__`` variable.
* ``differing-param-doc`` is now used for the differing part of the old ``missing-param-doc``,
and ``differing-type-doc`` for the differing part of the old ``missing-type-doc``.
Bug fixes
=========
* Fix a false positive of ``redundant-returns-doc``, occurred when the documented
function was using *yield* instead of *return*.
* Fix a false positive of ``missing-param-doc`` and ``missing-type-doc``,
occurred when a class docstring uses the ``For the parameters, see``
magic string but the class ``__init__`` docstring does not, or vice versa.
* Added proper exception type inference for ``missing-raises-doc``. Now:
.. code-block:: python
def my_func():
""""My function."""
ex = ValueError('foo')
raise ex
will properly be flagged for missing documentation of
``:raises ValueError:`` instead of ``:raises ex:``, among other scenarios.
* Fix false positives of ``missing-[raises|params|type]-doc`` due to not
recognizing valid keyword synonyms supported by Sphinx.
* More thorough validation in ``MessagesStore.register_messages()`` to detect
conflicts between a new message and any existing message id, symbol,
or ``old_names``.
* We now support having plugins that shares the same name and with each one
providing options.
A plugin can be logically split into multiple classes, each class providing
certain capabilities, all of them being tied under the same name. But when
two or more such classes are also adding options, then **pylint** crashed,
since it already added the first encountered section. Now, these should
work as expected.
.. code-block:: python
from pylint.checkers import BaseChecker
class DummyPlugin1(BaseChecker):
name = 'dummy_plugin'
msgs = {'I9061': ('Dummy short desc 01', 'dummy-message-01', 'Dummy long desc')}
options = (
('dummy_option_1', {
'type': 'string',
'metavar': '<string>',
'help': 'Dummy option 1',
}),
)
class DummyPlugin2(BaseChecker):
name = 'dummy_plugin'
msgs = {'I9060': ('Dummy short desc 02', 'dummy-message-02', 'Dummy long desc')}
options = (
('dummy_option_2', {
'type': 'string',
'metavar': '<string>',
'help': 'Dummy option 2',
}),
)
def register(linter):
linter.register_checker(DummyPlugin1(linter))
linter.register_checker(DummyPlugin2(linter))
* We do not yield ``unused-argument`` for singledispatch implementations and
do not warn about ``function-redefined`` for multiple implementations with same name.
.. code-block:: python
from functools import singledispatch
@singledispatch
def f(x):
return 2*x
@f.register(str)
def _(x):
return -1
@f.register(int)
@f.register(float)
def _(x):
return -x
* ``unused-variable`` checker has new functionality of warning about unused
variables in global module namespace. Since globals in module namespace
may be a part of exposed API, this check is disabled by default. For
enabling it, set ``allow-global-unused-variables`` option to false.
* Fix a false-positive ``logging-format-interpolation`` message, when format
specifications are used in formatted string. In general, these operations
are not always convertible to old-style formatting used by logging module.
* Added a new switch ``single-line-class-stmt`` to allow single-line declaration
of empty class bodies (as seen in the example below). Pylint won't emit a
``multiple-statements`` message when this option is enabled.
.. code-block:: python
class MyError(Exception): pass
* ``too-many-format-args`` and ``too-few-format-args`` are emitted correctly
(or not emitted at all, when exact count of elements in RHS cannot be
inferred) when starred expressions are used in RHS tuple. For example,
code block as shown below detects correctly that the used tuple has in
fact three elements, not two.
.. code-block:: python
meat = ['spam', 'ham']
print('%s%s%s' % ('eggs', *meat))
* ``cyclic-import`` checker supports local disable clauses. When one
of cycle imports was done in scope where disable clause was active,
cycle is not reported as violation.
Removed Changes
===============
* ``pylint-gui`` was removed, because it was deemed unfit for being included
in *pylint*. It had a couple of bugs and misfeatures, its usability was subpar
and since its development was neglected, we decided it is best to move on without it.
* The HTML reporter was removed, including the ``--output-format=html`` option.
It was lately a second class citizen in Pylint, being mostly neglected.
Since we now have the JSON reporter, it can be used as a basis for building
more prettier HTML reports than what Pylint can currently generate. This is
part of the effort of removing cruft from Pylint, by removing less used
features.
* The ``--files-output`` option was removed. While the same functionality cannot
be easily replicated, the JSON reporter, for instance, can be used as a basis
for generating the messages per each file.
* ``--required-attributes`` option was removed.
* ``--ignore-iface-methods`` option was removed.
* The ``--optimize-ast`` flag was removed.
The option was initially added for handling pathological cases,
such as joining too many strings using the addition operator, which
was leading pylint to have a recursion error when trying to figure
out what the string was. Unfortunately, we decided to ignore the
issue, since the pathological case would have happen when the
code was parsed by Python as well, without actually reaching the
runtime step and as such, we decided to remove the error altogether.
* ``epylint.py_run``'s *script* parameter was removed.
Now ``epylint.py_run`` is always using the underlying ``epylint.lint``
method from the current interpreter. This avoids some issues when multiple
instances of **pylint** are installed, which means that ``epylint.py_run``
might have ran a different ``epylint`` script than what was intended.
.. _`inline comment prefixes`: https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
---
### Doc Whatsnew 1 1.8 Full (`doc/whatsnew/1/1.8/full.rst`)
Full changelog
==============
What's New in Pylint 1.8.1?
---------------------------
Release date: 2017-12-15
* Wrong version number in __pkginfo__.
What's New in Pylint 1.8?
-------------------------
Release date: 2017-12-15
* Respect disable=... in config file when running with --py3k.
* New warning ``shallow-copy-environ`` added
Shallow copy of os.environ doesn't work as people may expect. os.environ
is not a dict object but rather a proxy object, so any changes made
on copy may have unexpected effects on os.environ
Instead of copy.copy(os.environ) method os.environ.copy() should be
used.
See https://bugs.python.org/issue15373 for details.
Closes #1301
* Do not display no-absolute-import warning multiple times per file.
* ``trailing-comma-tuple`` refactor check now extends to assignment with
more than one element (such as lists)
Closes #1713
* Fixing u'' string in :ref:`superfluous-parens` message
Closes #1420
* ``abstract-class-instantiated`` is now emitted for all inference paths.
Closes #1673
* Add set of predefined naming style to ease configuration of checking
naming conventions.
Closes #1013
* Added a new check, ``keyword-arg-before-vararg``
This is emitted for function definitions
in which keyword arguments are placed before variable
positional arguments (\*args).
This may lead to args list getting modified if keyword argument's value
is not provided in the function call assuming it will take default value
provided in the definition.
* The ``invalid-name`` check contains the name of the template that caused the failure
Closes #1176
* Using the -j flag won't start more child linters than needed.
Closes #1614
* Fix a false positive with bad-python3-import on relative imports
Closes #1608
* Added a new Python 3 check, ``non-ascii-bytes-literals``
Closes #1545
* Added a couple of new Python 3 checks for accessing dict methods in non-iterable context
* Protocol checks (:ref:`not-a-mapping`, :ref:`not-an-iterable` and co.) aren't emitted on classes with dynamic getattr
* Added a new warning, :ref:`bad-thread-instantiation`'
This message is emitted when the threading.Thread class does not
receive the target argument, but receives just one argument, which
is by default the group parameter.
Closes #1327
* In non-quiet mode, absolute path of used config file is logged to
standard error.
Closes #1519
* Raise meaningful exception for invalid reporter class being selected
When unknown reporter class will be selected as Pylint reporter,
meaningful error message would be raised instead of bare ``ImportError``
or ``AttributeError`` related to module or reporter class being not found.
Closes #1388
* Added a new Python 3 check for accessing removed functions from itertools
like ``izip`` or ``ifilterfalse``
* Added a new Python 3 check for accessing removed fields from the types
module like ``UnicodeType`` or ``XRangeType``
* Added a new Python 3 check for declaring a method ``next`` that would have
been treated as an iterator in Python 2 but a normal function in Python 3.
* Added a new key-value pair in json output. The key is ``message-id``
and the value is the message id.
Closes #1512
* Added a new Python 3.0 check for raising a StopIteration inside a generator.
The check about raising a StopIteration inside a generator is also valid if the exception
raised inherit from StopIteration.
Closes #1385
* Added a new warning, ``raising-format-tuple``, to detect multi-argument
exception construction instead of message string formatting.
* Added a new check for method of logging module that concatenate string via + operator
Closes #1479
* Added parameter for limiting number of suggestions in spellchecking checkers
* Fix a corner-case in ``consider-using-ternary`` checker.
When object ``A`` used in ``X and A or B`` was falsy in boolean context,
Pylint incorrectly emitted non-equivalent ternary-based suggestion.
After a change message is correctly not emitted for this case.
Closes #1559
* Added ``suggestion-mode`` configuration flag. When flag is enabled, informational
message is emitted instead of cryptic error message for attributes accessed on
c-extensions.
Closes #1466
* Fix a false positive ``useless-super-delegation`` message when
parameters default values are different from those used in the base class.
Closes #1085
* Disabling :ref:`wrong-import-order`', :ref:`wrong-import-position`', or
:ref:`ungrouped-imports`' for a single line now prevents that line from
triggering violations on subsequent lines.
Closes #1336
* Added a new Python check for inconsistent return statements inside method or function.
Closes #1267
* Fix ``superfluous-parens`` false positive related to handling logical statements
involving ``in`` operator.
Closes #574
* ``function-redefined`` message is no longer emitted for functions and
methods which names matches dummy variable name regular expression.
Closes #1369
* Fix ``missing-param-doc`` and ``missing-type-doc`` false positives when
mixing ``Args`` and ``Keyword Args`` in Google docstring.
Closes #1409
* Fix ``missing-docstring`` false negatives when modules, classes, or methods
consist of compound statements that exceed the ``docstring-min-length``
* Fix ``useless-else-on-loop`` false positives when break statements are
deeply nested inside loop.
Closes #1661
* Fix no ``wrong-import-order`` message emitted on ordering of first and third party
libraries. With this fix, pylint distinguishes third and first party
modules when checking import order.
Closes #1702
* Fix ``pylint disable=fixme`` directives ignored for comments following the
last statement in a file.
Closes #1681
* Fix ``line-too-long`` message deactivated by wrong disable directive.
The directive ``disable=fixme`` doesn't deactivate anymore the emission
of ``line-too-long`` message for long commented lines.
Closes #1741
* If the rcfile specified on the command line doesn't exist, then an
IOError exception is raised.
Closes #1747
* Fix the wrong scope of the ``disable=`` directive after a commented line.
For example when a ``disable=line-too-long`` directive is at the end of
a long commented line, it no longer disables the emission of ``line-too-long``
message for lines that follow.
Closes #1742
---
### Doc Whatsnew 1 1.8 Index (`doc/whatsnew/1/1.8/index.rst`)
**************************
What's New In Pylint 1.8
**************************
.. include:: ../../full_changelog_explanation.rst
.. include:: ../../summary_explanation.rst
.. toctree::
:maxdepth: 2
summary.rst
full.rst
---
### Doc Whatsnew 1 1.8 Summary (`doc/whatsnew/1/1.8/summary.rst`)
:Release: 1.8
:Date: 2017-12-15
Summary -- Release highlights
=============================
* None so far
New checkers
============
* A new check was added, ``shallow-copy-environ``.
This warning message is emitted when shallow copy of os.environ is created.
Shallow copy of os.environ doesn't work as people may expect. os.environ
is not a dict object but rather a proxy object, so any changes made
on copy may have unexpected effects on os.environ
Instead of copy.copy(os.environ) method os.environ.copy() should be used.
See https://bugs.python.org/issue15373 for details.
.. code-block:: python
import copy
import os
wrong_env_copy = copy.copy(os.environ) # will emit pylint warning
wrong_env_copy['ENV_VAR'] = 'new_value' # changes os.environ
assert os.environ['ENV_VAR'] == 'new_value'
good_env_copy = dict(os.environ) # the right way
good_env_copy['ENV_VAR'] = 'different_value' # doesn't change os.environ
assert os.environ['ENV_VAR'] == 'new_value'
* A new check was added, ``keyword-arg-before-vararg``.
This warning message is emitted when a function is defined with a keyword
argument appearing before variable-length positional arguments (\*args).
This may lead to args list getting modified if keyword argument's value is
not provided in the function call assuming it will take default value provided
in the definition.
.. rstcheck: ignore-next-code-block
.. code-block:: python
def foo(a, b=3, *args):
print(a, b, args)
# Case1: a=0, b=2, args=(4,5)
foo(0,2,4,5) # 0 2 (4,5) ==> Observed values are same as expected values
# Case2: a=0, b=<default_value>, args=(4,5)
foo(0,4,5) # 0 4 (5,) ==> args list got modified as well as the observed value of b
# Case3: Syntax Error if tried as follows
foo(0,b=2,4,5) # syntax error
* A new check was added, ``simplify-boolean-expression``.
This message is emitted when ``consider-using-ternary`` check would emit
not equivalent code, due to truthy element being falsy in boolean context.
.. code-block:: python
value = condition and False or other_value
This flawed construct may be simplified to:
.. code-block:: python
value = other_value
* A new check was added, ``bad-thread-instantiation``.
This message is emitted when the threading.Thread class does not
receive the target argument, but receives just one argument, which
is by default the group parameter.
In the following example, the instantiation will fail, which is definitely
not desired:
.. code-block:: python
import threading
threading.Thread(lambda: print(1)) # Oups, this is the group parameter
* A new Python 3 checker was added to warn about accessing functions that have been
removed from the itertools module ``izip``, ``imap``, ``iflter``, ``izip_longest``, and ``ifilterfalse``.
.. code-block:: python
from itertools import izip
print(list(izip([1, 2], [3])))
Instead use ``six.moves`` to import a Python 2 and Python 3 compatible function:
.. code-block:: python
from six.moves import zip
print(list(zip([1, 2], [3])))
* A new Python 3 checker was added to warn about accessing deprecated fields from
the types module like ``ListType`` or ``IntType``
.. code-block:: python
from types import ListType
print(isinstance([], ListType))
Instead use the declarations in the builtin namespace:
.. code-block:: python
print(isinstance([], list))
* A new Python 3 checker was added to warn about declaring a ``next`` method that
would have implemented the ``Iterator`` protocol in Python 2 but is now a normal
method in Python 3.
.. code-block:: python
class Foo(object):
def next(self):
return 42
Instead implement a ``__next__`` method and use ``six.Iterator`` as a base class
or alias ``next`` to ``__next__``:
.. code-block:: python
class Foo(object):
def __next__(self):
return 42
next = __next__
* Three new Python 3 checkers were added to warn about using dictionary methods
in non-iterating contexts.
For example, the following are returning iterators in Python 3::
.. code-block:: python
d = {}
d.keys()[0]
d.items()[0]
d.values() + d.keys()
* A new Python 3 porting check was added, ``non-ascii-bytes-literals``
This message is emitted whenever we detect that a bytes string contain
non-ASCII characters, which results in a SyntaxError on Python 3.
* A new warning, ``raising-format-tuple``, will catch situations where the
intent was likely raising an exception with a formatted message string,
but the actual code did omit the formatting and instead passes template
string and value parameters as separate arguments to the exception
constructor. So it detects things like
.. code-block:: python
raise SomeError('message about %s', foo)
raise SomeError('message about {}', foo)
which likely were meant instead as
.. code-block:: python
raise SomeError('message about %s' % foo)
raise SomeError('message about {}'.format(foo))
This warning can be ignored on projects which deliberately use lazy
formatting of messages in all user-facing exception handlers.
* Following the recommendations of PEP479_ ,a new Python 3.0 checker was added to warn about raising a ``StopIteration`` inside
a generator. Raising a ``StopIteration`` inside a generator may be due a direct call
to ``raise StopIteration``:
.. code-block:: python
def gen_stopiter():
yield 1
yield 2
yield 3
raise StopIteration
Instead use a simple ``return`` statement
.. code-block:: python
def gen_stopiter():
yield 1
yield 2
yield 3
return
Raising a ``StopIteration`` may also be due to the call to ``next`` function with a generator
as argument:
.. code-block:: python
def gen_next_raises_stopiter():
g = gen_ok()
while True:
yield next(g)
In this case, surround the call to ``next`` with a try/except block:
.. code-block:: python
def gen_next_raises_stopiter():
g = gen_ok()
while True:
try:
yield next(g)
except StopIteration:
return
* The check about raising a StopIteration inside a generator is also valid if the exception
raised inherit from StopIteration.
Closes #1385
.. _PEP479: https://peps.python.org/pep-0479
* A new Python checker was added to warn about using a ``+`` operator inside call of logging methods
when one of the operands is a literal string:
.. code-block:: python
import logging
var = "123"
logging.log(logging.INFO, "Var: " + var)
Instead use formatted string and positional arguments :
.. code-block:: python
import logging
var = "123"
logging.log(logging.INFO, "Var: %s", var)
* A new Python checker was added to warn about ``inconsistent-return-statements``. A function or a method
has inconsistent return statements if it returns both explicit and implicit values :
.. code-block:: python
def mix_implicit_explicit_returns(arg):
if arg < 10:
return True
elif arg < 20:
return
According to PEP8_, if any return statement returns an expression,
any return statements where no value is returned should explicitly state this as return None,
and an explicit return statement should be present at the end of the function (if reachable).
Thus, the previous function should be written:
.. code-block:: python
def mix_implicit_explicit_returns(arg):
if arg < 10:
return True
elif arg < 20:
return None
Closes #1267
.. _PEP8: https://peps.python.org/pep-0008
Other Changes
=============
* Fixing u'' string in :ref:`superfluous-parens` message.
* Configuration options of invalid name checker are significantly redesigned.
Predefined rules for common naming styles were introduced. For typical
setups, user friendly options like ``--function-naming-style=camelCase`` may
be used in place of hand-written regular expressions. Default linter config
enforce PEP8-compatible naming style. See documentation for details.
* Raise meaningful exception in case of invalid reporter class (output format)
being selected.
* The docparams extension now allows a property docstring to document both
the property and the setter. Therefore setters can also have no docstring.
* The docparams extension now understands property type syntax.
.. code-block:: python
class Foo(object):
@property
def foo(self):
"""My Sphinx style docstring description.
:type: int
"""
return 10
.. code-block:: python
class Foo(object):
@property
def foo(self):
"""int: My Numpy and Google docstring style description."""
return 10
* In case of ``--output-format=json``, the dictionary returned holds a new key-value pair.
The key is ``message-id`` and the value the message id.
* Spelling checker has a new configuration parameter ``max-spelling-suggestions``, which
affects maximum count of suggestions included in emitted message.
* The **:ref:`invalid-name`** check contains the name of the template that caused the failure.
For the given code, **pylint** used to emit ``invalid-name`` in the form ``Invalid constant name var``,
without offering any context why ``var`` is not such a good name.
With this change, it is now more clear what should be improved for a name to be accepted according to
its corresponding template.
* New configuration flag, ``suggestion-mode`` was introduced. When enabled, pylint would
attempt to emit user-friendly suggestions instead of spurious errors for some known
false-positive scenarios. Flag is enabled by default.
* ``superfluous-parens`` is no longer wrongly emitted for logical statements involving ``in`` operator
(see example below for what used to be false-positive).
.. code-block:: python
foo = None
if 'bar' in (foo or {}):
pass
* Redefinition of dummy function is now possible. ``function-redefined`` message won't be emitted anymore when
dummy functions are redefined.
* ``missing-param-doc`` and ``missing-type-doc`` are no longer emitted when
``Args`` and ``Keyword Args`` are mixed in Google docstring.
* Fix of false positive ``useless-super-delegation`` message when
parameters default values are different from those used in the base class.
* Fix of false positive ``useless-else-on-loop`` message when break statements
are deeply nested inside loop.
* The Python 3 porting checker no longer emits multiple ``no-absolute-import`` per file.
* The Python 3 porting checker respects disabled checkers found in the config file.
* Modules, classes, or methods consist of compound statements that exceed the ``docstring-min-length``
are now correctly emitting ``missing-docstring``
* Fix no ``wrong-import-order`` message emitted on ordering of first and third party libraries.
With this fix, pylint distinguishes first and third party modules when checking
import order.
* Fix the ignored ``pylint disable=fixme`` directives for comments following
the last statement in a file.
* Fix ``line-too-long`` message deactivated by wrong disable directive.
The directive ``disable=fixme`` doesn't deactivate anymore the emission
of ``line-too-long`` message for long commented lines.
* If the rcfile specified on the command line doesn't exist, then an
IOError exception is raised.
* Fix the wrong scope of ``disable=`` directive after a commented line.
For example when a ``disable=line-too-long`` directive is at the end of a
long commented line, it no longer disables the emission of ``line-too-long``
message for lines that follow.
---
### Doc Whatsnew 1 1.9 Full (`doc/whatsnew/1/1.9/full.rst`)
Full changelog
==============
What's New in Pylint 1.9?
-------------------------
Release date: 2018-05-15
* Added two new Python 3 porting checks, ``exception-escape`` and ``comprehension-escape``
These two are emitted whenever pylint detects that a variable defined in the
said blocks is used outside of the given block. On Python 3 these values are deleted.
* Added a new ``deprecated-sys-function``, emitted when accessing removed sys members.
* Added ``xreadlines-attribute``, emitted when the ``xreadlines()`` attribute is accessed.
* The Python 3 porting mode can now run with Python 3 as well.
* docparams extension allows abstract methods to document what overriding
implementations should return, and to raise NotImplementedError without
documenting it.
Closes #2044
* Special methods do not count towards ``too-few-methods``,
and are considered part of the public API.
* Enum classes do not trigger ``too-few-methods``
Closes #605
* Added a new Python 2/3 check for accessing ``operator.div``, which is removed in Python 3
Closes #1936
* Added a new Python 2/3 check for accessing removed urllib functions
Closes #1997
---
### Doc Whatsnew 1 1.9 Index (`doc/whatsnew/1/1.9/index.rst`)
**************************
What's New In Pylint 1.9
**************************
.. include:: ../../full_changelog_explanation.rst
.. include:: ../../summary_explanation.rst
.. toctree::
:maxdepth: 2
summary.rst
full.rst
---
### Doc Whatsnew 1 1.9 Summary (`doc/whatsnew/1/1.9/summary.rst`)
:Release: 1.9
:Date: 2018-05-15
Summary -- Release highlights
=============================
* None so far
New checkers
============
* A new Python 3 checker was added to warn about the removed ``operator.div`` function.
* A new Python 3 checker was added to warn about accessing functions that have been
moved from the urllib module in corresponding subpackages, such as ``urllib.request``.
.. code-block:: python
from urllib import urlencode
Instead the previous code should use ``urllib.parse`` or ``six.moves`` to import a
module in a Python 2 and 3 compatible fashion:
.. code-block:: python
from six.moves.urllib.parse import urlencode
To have this working on Python 3 as well, please use the ``six`` library:
.. code-block:: python
six.reraise(Exception, "value", tb)
* A new check was added to warn about using unicode raw string literals. This is
a syntax error in Python 3:
.. rstcheck: ignore-next-code-block
.. code-block:: python
a = ur'...'
* Added a new ``deprecated-sys-function`` check, emitted when accessing removed ``sys`` members.
* Added ``xreadlines-attribute`` check, emitted when the ``xreadlines()`` attribute is accessed
on a file object.
* Added two new Python 3 porting checks, ``exception-escape`` and ``comprehension-escape``
These two are emitted whenever pylint detects that a variable defined in the
said blocks is used outside of the given block. On Python 3 these values are deleted.
.. code-block:: python
try:
1/0
except ZeroDivisionError as exc:
...
print(exc) # This will raise a NameError on Python 3
[i for i in some_iterator if some_condition(i)]
print(i) # This will raise a NameError on Python 3
Other Changes
=============
* ``defaultdict`` and subclasses of ``dict`` are now handled for `dict-iter-*` checks. That
means that the following code will now emit warnings for when ``iteritems`` and friends
are accessed:
.. code-block:: python
some_dict = defaultdict(list)
...
some_dict.iterkeys()
* Enum classes no longer trigger ``too-few-methods``
* Special methods now count towards ``too-few-methods``,
and are considered part of the public API.
They are still not counted towards the number of methods for
``too-many-methods``.
* docparams allows abstract methods to document returns documentation even
if the default implementation does not return something.
They also no longer need to document raising a NotImplementedError.
---
### Doc Whatsnew 2 2.0 Full (`doc/whatsnew/2/2.0/full.rst`)
Full changelog
==============
What's New in Pylint 2.0?
-------------------------
Release date: 2018-07-15
* ``try-except-raise`` should not be emitted if there are any parent exception class handlers.
Closes #2284
* ``trailing-comma-tuple`` can be emitted for ``return`` statements as well.
Closes #2269
* Fix a false positive ``inconsistent-return-statements`` message when exception is raised
inside an else statement.
Closes #1782
* ``ImportFrom`` nodes correctly use the full name for the import sorting checks.
Closes #2181
* [].extend and similar builtin operations don't emit `dict-*-not-iterating` with the Python 3 porting checker
Closes #2187
* Add a check ``consider-using-dict-comprehension`` which is emitted if for dict initialization
the old style with list comprehensions is used.
* Add a check ``consider-using-set-comprehension`` which is emitted if for set initialization
the old style with list comprehensions is used.
* ``logging-not-lazy`` is emitted whenever pylint infers that a string is built with addition
Closes #2193
* Add a check ``chained-comparison`` which is emitted if a boolean operation can be simplified
by chaining some of its operations.
e.g "a < b and b < c", can be simplified as "a < b < c".
Closes #2032
* Add a check ``consider-using-in`` for comparisons of a variable against
multiple values with "==" and "or"s instead of checking if the variable
is contained "in" a tuple of those values.
* ``in`` is considered iterating context for some of the Python 3 porting checkers
Closes #2186
* Add ``--ignore-none`` flag to control if pylint should warn about ``no-member`` where the owner is None
* Fix a false positive related to ``too-many-arguments`` and bounded ``__get__`` methods
Closes #2172
* ``mcs`` as the first parameter of metaclass's ``__new__`` method was replaced by ``cls``
Closes #2028
* ``assignment-from-no-return`` considers methods as well.
Closes #2081
* Support typing.TYPE_CHECKING for *:ref:`unused-import`* errors
Closes #1948
* Inferred classes at a function level no longer emit ``invalid-name``
when they don't respect the variable regular expression
Closes #1049
* Added basic support for postponed evaluation of function annotations.
Closes #2069
* Fix a bug with ``missing-kwoa`` and va