Setup Pylint pre-commit hook

Posted by Moser on 28 Oct 2020

A short guide on the Pylint hook for pre-commit.

1) Install pre-commit

In a Python project you should add the pre-commit package to your development requirements (requirements-dev.txt, Pipfile or whatever you are using).

You can also install it directly via pip:

pip install pre-commit

Check the installation by running

pre-commit --version

2) Add a config file

Create a file called .pre-commit-config.yaml in the root directory of your git repository and add the following content:

repos:
  - repo: https://github.com/pycqa/pylint
    rev: pylint-2.6.0
    hooks:
    -   id: pylint

3) Install the hook

The following command will install a small script to .git/hooks which calls the pre-commit tool.

pre-commit install

4) Try to commit a file with an issue

Prepare a broken file:

echo "import foobaz" > test.py && git add test.py

When you try to commit this, pylint will fail and stop you from doing the commit.

$ git commit -m "Add test.py"
[INFO] Initializing environment for https://github.com/pycqa/pylint.
[INFO] Installing environment for https://github.com/pycqa/pylint.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
pylint...................................................................Failed
- hook id: pylint
- exit code: 22

************* Module test
test.py:1:0: C0114: Missing module docstring (missing-module-docstring)
test.py:1:0: E0401: Unable to import 'foobaz' (import-error)
test.py:1:0: W0611: Unused import foobaz (unused-import)

---------------------------------------------------------------------
Your code has been rated at -60.00/10 (previous run: 2.22/10, -62.22)

$ git status --short
A  test.py

When pre-commit runs for the first time, it installs pylint into a virtualenv in a special folder in ~/.cache/pre-commit. This installation is reused on following runs.

Disable the hook for a commit

Some times you may want to commit a file even though it has an issue. You can disable the pylint hook by setting a environment variable, e.g. like this:

SKIP=pylint git commit ...

If want to disable all hooks while committing, use the --no-verify/-n option:

git commit -n ...

More hooks

There are dozens of tools that can be run in a pre-commit hook. In my Python projects I usually have pylint, black and isort activated. Check out the full list.

Run Pylint automatically on your project

I created a product that runs Pylint and other linters on your Github projects automatically: Please have a look at PyCodeQual.