2 min read

Code formatting a Python project in 2022

For those who want a quick solution without reading all of PEP 8. The Black Python module has a fully automated solution for you.

Black logo
Isaac Bythewood Isaac Bythewood
July 30, 2022

It's not always worth hand formatting every line of code. You can dramatically increase the speed at which you write code by ignoring formatting entirely and making use of code formatters like Black for Python. I've also found that using Black makes Git commits and diffs much cleaner by removing human inconsistency from the equation. To get straight to the point I install Black, Flake8, and isort on all of my projects. You can use your preferred Python package manager, I use pipenv and add these dependencies to my Pipfile under [dev-packages].

You'll then want to make a file named .isort.cfg and configure isort to use black's formatting style so that when you sort dependencies you aren't bouncing between the two's opinionated styles.

I then configure Flake8 in the file .flake8 to make sure it's not complaining about Black's opinionated styling.

As a small bonus if you use Visual Studio Code you can install the Python Extension and get built in formatting support. I use three extra config lines to enable Flake8, add Black formatting, and auto format on save.

If you are using these tools manually you can run Black, isort, or Flake8 directly on a file. With Pipenv you'd use something like pipenv run black python_file.py and have your code automatically formatted. These are all very popular tools though and I suggest taking a look at your IDE's documentation use them how your IDE suggests. I've also added lint and format commands with a Makefile too if you'd like an solution that isn't tied to an IDE.

That's all you need to do to have well formatted Python code in 2022. Let modern tooling do the work for you.

Related posts

Some posts in similar tags to this one.

EditorConfig website
Using EditorConfig to improve coding style consistency
EditorConfig has been around for almost a decade at this point. It is widely supported by many editors natively and many more with plugins.
Isaac Bythewood Isaac Bythewood
May 21, 2022
Caddy website
Caddy configuration for Django with some sensible defaults
Caddy is a great web server with sensible defaults but there a few things that I need to configure to have perfect synergy with Django.
Isaac Bythewood Isaac Bythewood
June 04, 2022
CodeMirror website
Using CodeMirror to show formatted code in Wagtail
Going through all the steps to use CodeMirror with Wagtail to show formatted code on the frontend of your site.
Isaac Bythewood Isaac Bythewood
June 11, 2022
© 2024 Isaac Bythewood. Some rights reserved.