MSDN Documentation

Python Tools

Linting in Python Tools

Linting is the process of analyzing code to detect and flag programming errors, bugs, stylistic errors, and suspicious constructs. Integrated linting within your Python development tools can significantly improve code quality, maintainability, and adherence to best practices. Microsoft's Python tools provide robust support for popular linters like Pylint, Flake8, and Mypy.

Configuring Linters

To configure linting, navigate to your project's settings or preferences. In Visual Studio, this is typically under Tools > Options > Python > Linting.

You can enable or disable specific linters, set paths to their executables, and configure their arguments. Many linters can also be configured via dedicated configuration files (e.g., .pylintrc, setup.cfg, pyproject.toml). The tools will automatically pick up these configurations when available.

Using Pylint

Pylint is a powerful linter that checks for errors, enforces a coding standard, and searches for bad smells in the code.

Enabling Pylint

Ensure Pylint is installed in your Python environment:

pip install pylint

Then, enable it in your IDE's settings. Pylint provides extensive configuration options, allowing you to disable specific checks or customize the report.

Example Pylint Configuration (.pylintrc)

[MESSAGES CONTROL]
disable=C0114, C0115, C0116, W0611

[FORMAT]
max-line-length = 100
indent-size = 4

When Pylint runs, you'll see findings directly in your editor, often highlighted with underlines and messages in a dedicated output window.

Example Pylint output might look like:
your_module.py:10:0: C0301: Line too long (105/100) (line-too-long)
your_module.py:5:0: W0611: Unused import 'os' (unused-import)

Using Flake8

Flake8 is a wrapper around PyFlakes, pycodestyle, and McCabe. It checks for style guide violations and potential errors.

Enabling Flake8

Install Flake8:

pip install flake8

Enable it in your IDE. Flake8 also supports configuration files (e.g., .flake8 or setup.cfg).

Example Flake8 Configuration (setup.cfg)

[flake8]
max-line-length = 100
exclude = .git,__pycache__,docs/source/conf.py,old,build,dist
ignore = E203, W503

Flake8 errors are also displayed inline within your code editor.

Using Mypy for Type Checking

Mypy is a static type checker for Python. It helps catch type errors early in the development cycle, especially beneficial for larger projects.

Enabling Mypy

Install Mypy:

pip install mypy

Enable Mypy in your IDE's settings. Mypy can be configured via a mypy.ini file or pyproject.toml.

Example Mypy Configuration (mypy.ini)

[mypy]
plugins =
    pydantic.mypy
ignore_missing_imports = True
strict = True

Mypy will report type inconsistencies, such as passing an argument of the wrong type to a function.

Benefits of Linting

Further Reading