Member-only story
The Easy Python Auto-code Formatting Guide
Set them up just once and write and auto-format your code upon commits — hassle-free with these tools.
The easy to read and understand syntax of Python has made it the most popular programming language today — and with good reason. The wide variety of use-cases of Python are so diverse that software engineering, machine learning, and data science with all of having varying and complex usages for it.
One of the most overlooked yet essential areas in writing clean Python code include the murky waters of the need for good formatting and code checks.
Suffice to say, in this day of automation in every aspect of life, this particular step in code reviews can also easily be done without too much manual effort.
There are a few tools that help you save some precious time and mental energy for more important matters than formatting your code each time before a git commit.
Here are some of them:
- pre-commit hooks,
- black
- isort
Let’s go over and learn how to set them up for a Python project, one by one.
Installing and using pre-commit hooks
The pre-commit hooks do exactly as it says on the tin — they run certain scripts that check your code against errors, trailing whitespaced, run some formatting tools, and many other useful checks in a code review process.
For us, we will go through two important hooks excluding some of the usual ones.
Let’s install the library first (I am assuming you’re using a virtual environment already):
pip install pre-commit
Check the version after installing with this and it should output the version for you as a sanity check:
$ pre-commit --versionpre-commit 2.17.0
Here’s the thing: in order to go with the easy way to set up auto-formatting tools, you need a particular git configuration file in your root project directory.
Let’s go make that now.