Make Your Python Code Cleaner in One Easy Step
24 Oct 2022Everybody knows that code needs to be understandable and easy to read. But at the same time, everybody forgets to write typings, sort imports, or follow PEP8. There is a solution — pre-commit.
This tool will trigger different hooks every time you commit your code. So, let’s integrate it into our project.
Installation
Let’s install pre-commit into the environment
pip install pre-commit
Then we need to add two files to the root directory of your project
.pre-commit-config.yaml
pyproject.toml
And now, you have to install the hooks that you’ve added.
pre-commit install
Usage
git commit -m "new brave code"
Yep, that’s it. Now, every time you’ll commit your code, those hooks will trigger. And automatically:
- sort imports
- format code for PEP8
- check the correctness of your yaml and json files
And mypy will not pass your code if it’s not statically typed. So you’ll have to use typings in the right way.
Explanation
In the .pre-commit-config.yaml
file, you specify which hooks you will use. For example, in the provided file, we use black code formatter of version 22.3.0. And ask not to change ‘
to "
using a --skip-string-normalization
flag.
In the pyproject.toml
you specify parameters for those individual hooks. For example, you set the maximum line length to 88.