Blog
Apr 10, 2022
Apr 21, 2022

Keep your python code tidy with pre-commit

Identify simple problems before reviewing the code with pre-commit. Pre-commit uses git hooks to catch your little typos before they reach the git tree. Automatically format your code, run a linter, type check, check configuration files, etc.

First we need to install pre-commit, which is a framework for managing and maintaining multi-language pre-commit hooks:

pip install pre-commit pre-commit --version

Pre-commit hooks must be defined in .pre-commit-config.yaml, here is an example using two hooks:

repos: - repo: https://github.com/psf/black rev: stable hooks: - id: black args: [--config=pyproject.toml] - repo: https://github.com/hakancelik96/unimport rev: stable hooks: - id: unimport args: [--remove, --requirements, --include-star-import, --ignore-init, --gitignore]
  • black: a Python code formatter
  • unimport: a formatter for finding and removing unused import statement

Now that your pre-commit configuration is setup, all you have to do is to run once:

pre-commmit install

Now, hooks will be executed on every commit!

Julien LE PÊCHEUR

Julien LE PÊCHEUR

Software developer in France.

Leave a Reply

Related Posts

Categories