Make Your Python Code Cleaner in One Easy Step
You can read the original version of this article on my blog.
Everybody knows that code needs to be understandable and easy to read. But at the same time, everybody forgets to type annotations, sort imports, or follow PEP8. There is a solution to this — pre-commit.
This tool will trigger hooks every time you commit your code. Here’s how to integrate it into a project.
Installation
First, we install pre-commit into the environment.
pip install pre-commit
Then, we need to add two files to the root directory of the project.
.pre-commit-config.yaml
pyproject.toml
Next, you should install the hooks that you’ve added.
pre-commit install
Usage
git commit -m "new brave code"
That’s it. Now, every time you commit your code, those hooks will trigger and automatically
- sort imports,
- format code according to PEP,
- check the correctness of your yaml and json files.
And mypy won’t pass your code unless it’s statically typed. So you’ll have to type annotations the right way.
Explanation
In the .pre-commit-config.yaml
file, you specify which hooks you’ll use. For example, in the provided file, we use the black code formatter (version 22.3.0) and ask not to change ‘
to "
using a --skip-string-normalization
flag.
In pyproject.toml
you specify the parameters for those individual hooks. For example, you set the maximum line length to 88.
That’s it! As easy as it sounds.