When I first started working in software development teams, I can remember heated discussions on pull requests on a few occasions. Typically these were when I or other developers reviewed code that didn’t meet formatting rules that were felt best for that piece of work. It didn’t matter whether the rules in question were in code, documented in a README or just held in a developers head, the simple fact that something was wrong on the project meant the author needed to make changes, be severely reprimanded and never make the mistake again. The tabs vs spaces episode on Silicon Valley is a really nice summary of how one such conversation might go.
We’d spend inordinate amounts of time defining what the rules for formatting should be and way too long arguing over why any particular format was better than another. This has also brought out the worst in myself and other devs and most of the time resulted the most opinionated or developer who shouted the loudest getting their own way. Not a great way to be working as a team.
Black is an “Uncomprimising” code formatter for Python with one aim to make code review faster and bring the focus back to your content. With black, code is formatted according to PEP8 and looks the same on every project it’s used on. You run black, your code is formatted and everybody moves on with their lives.
Since using black on multiple projects, it’s been possible to quickly skip over these sorts of discussions on PRs and make them a part of an automated check in a ci:
black --check .
This will fail if your Python code doesn’t conform to blacks formatting rules. It’s better to make the pipeline be the bearer of the bad news that another commit is neccessary for the PR author, rather than burden another developer with it. You can use this in conjunction with linters like flake8 and pylint to check other formatting issues with your code. The nice thing with black is you can also quickly reformat your code to meet blacks rules using:
In summary, use black to format your code and go back to worrying about more important things, like living your life.
Simon Willison’s tweet this morning is what inspired this post:
Continuing to marvel at how much of my Python programming time I used to spend thinking about coding style before I embraced Black and stopped thinking about it at all— Simon Willison (@simonw) November 3, 2020
If you liked this post, follow me on twitter or join my newsletter below. You'll get updates on new content here and around the web on topics like Python, automation and the cloud once a week.