Linting Python code using ruff or flake8: simple, fast, free and no false positives

Linting Python code using ruff or flake8: fast, free and no false positives

Static code analysis can help automatically find minor coding issues and style deviations. This helps especially if several people are collaborating on the same code.

With a dynamically typed language such as Python, since there is no build step, it can be helpful to have some static code analysis in place, to for example catch silly mistakes with indentation, or more serious mistakes such as incorrect exception handling.

Linting can be though of as a kind of lightweight form of static code analysis, looking for code style and layout issues. Because Python uses indenting to communicate control flow and scope (rather than the brackets used by many C++ or C# styled languages including Java), then automatically detecting such spacing issues can be critical.

When selecting a Python linter, there are many options to chose from. I like to use flake8 as it is simple, reliable, fast and has very low rate of false positives. It can still detect more complex issues such as incorrect exception handling.

ruff - linter and formatter

A new and even faster option: ruff - very fast and also formats the code, and its default settings seem to be more practical than flake8.

Installation

To install ruff (via pip):

python -m pip install ruff --quiet

Execution

To lint:

    ruff check src

To format:

    ruff format src

To configure:

Either add sections to pyproject.toml if you have one, OR add a file ruff.toml.
See the ruff docs for details.

flake8 - simple linter

Installation

To install flake8 (via pip):

python -m pip install flake8 --quiet

Execution

To run, assuming that source code is under 'src' folder, use a command like:

python -m flake8 ./src


For a more complete example with some disabled rules, see the following bash script:


# so future errors halt the script.
set -e

echo Linting ...

# Disable less useful errors
# - ref https://www.flake8rules.com/
#
# E302 Expected 2 blank lines
# E305 Expected 2 blank lines after end of function or class
# E501 Line too long (82 > 79 characters)
FLAKE8_TO_IGNORE=E302,E305,E501

python -m flake8 --extend-ignore $FLAKE8_TO_IGNORE ./src

echo [done]


The same code is also available as a gist.


For more details about flake8, see:

- quickstart: https://flake8.pycqa.org/en/latest/index.html#quickstart

- rules: https://www.flake8rules.com/


Alternatives to flake8 or ruff

For other options to lint Python code (including code style) see the following articles:

  - https://codilime.com/blog/python-code-quality-linters/

  - https://inventwithpython.com/blog/2022/11/19/python-linter-comparison-2022-pylint-vs-pyflakes-vs-flake8-vs-autopep8-vs-bandit-vs-prospector-vs-pylama-vs-pyroma-vs-black-vs-mypy-vs-radon-vs-mccabe/


Comments