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.

Code formatting a Python project in 2022
Isaac Bythewood Isaac Bythewood
2022-07-30

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.


Some posts in similar tags to this one.

Capturing screenshots with Chromium using Python
Capturing screenshots with Chromium using Python
Sometimes you need to take screenshots of the web and Chromium provides an easy way to do that.
Isaac Bythewood Isaac Bythewood
2022-08-06
Finding broken external links on websites using Scrapy
Finding broken external links on websites using Scrapy
Broken links are a problem for any content driven website as it ages, find them quickly and easily with Scrapy.
Isaac Bythewood Isaac Bythewood
2022-07-23
Make your own new tab browser extension in 50 lines of code
Make your own new tab browser extension in 50 lines of code
There are plenty of home page and new tab replacement extensions on the Chrome Web Store that you could use, but why not make your own if it's easy?
Isaac Bythewood Isaac Bythewood
2022-07-09