Improve Python code with Pylint

While linting will not fix all your problems automagically, it’s an interesting step you can add to improve your code.

Disclaimer

It’s only an introduction to the tool. There are many options for the commands I won’t cover here.

Linting vs. debugging

It’s essential to know the difference between linting and debugging.

Linting involves static analysis, while debugging allows you to catch errors while executing code.

Linters can’t replace debuggers. It’s not meant to analyze code dynamically.

Still, it can improve the code significantly with minimum effort:

  • it can catch bad practices
  • it improves readability
  • it can spot doublons

There are other advantages, but these should be interesting.

How to lint Python code

As usual, there are many solutions, but the easiest one is probably to install Pylint:

  • you can install it as a simple package: pip install pylint
  • it has a great documentation
  • it’s easy to start with default settings
  • you can customize linting rules
  • you can extend it with plugins

To use it, just type the following:

pip install pylint
pylint mymodule.py

You’ll get a score that can be improved by fixing linting errors. Don’t worry, if, for some valid reason, you don’t want to apply the suggested fix, you can disable it at various levels:

  • globally in the ~/.pylintrc file (at the root of your home directory)
  • per project with a custom .pylintrc file at the root
  • in the code, with special comments that start with # pylint: disable-next= followed by the error code

N.B.: There are other directories like /etc/pylintrc or .config/pylintrc

Pylint provides a specific code for each error. For example, missing-function-docstring means your function does not contain necessary doc.

PEP8?

Pylint follows PEP8 styles.

These guidelines are coding standards for Python. That’s why you won’t find the following in most Python scripts:

import os, sys

But this instead:

import os
import sys

Pylint use these rules to spot non-standard code and other bad practices.

I get too much extra-work!

It’s undeniably an additional step, but hopefully for the best, and you can speed up the operation with an additional package:

pip install autopep8
autopep8 --aggressive mymodule.py

It can fix many linting errors automatically for you.

Be careful, though. As the name suggests, the --aggressive mode can be a bit too much…

Pylint in the IDE

Pylint can be used as a command-line tool, but you can also integrate it directly in your favorite IDE. See this link

Pylint as pre-commit

You can check code before committing anything with the pre-commit hook.

Such approach is pretty common in dev and blocks commits that do not respect linting rules.

Wrap up

Using Pylint can improve your process. While static analysis is certainly not the ultimate approach, it’s worth it.