Formatting and Styling Your Code Consistently

Intuitive Python — by David Muller (13 / 41)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Detecting Problems Early | TOC | Wrapping Up 👉

Using a program to automatically format code won’t necessarily prevent bugs, but it can improve the maintainability of your project over time by bringing consistency, readability, and reducing the number of “tabs versus spaces” style arguments your team has. Some languages include automatic code formatters as part of their implementation — go comes with gofmt, for example.

Python does not have a built-in mechanism for formatting code like go does, but a tool named black[34] is the Python Software Foundation’s “blessed” application for automatically formatting Python code.[35] black should be one of the tools in your tool box, and many popular Python projects and corporations (for example, Dropbox, Facebook, and Mozilla) use black to automatically format their Python code.

black bills itself as, “the uncompromising Python code formatter.” In general, it cannot be configured or have any of its formatting behaviors meaningfully changed. It formats Python code the way it will, and you are required to accept it. Its name was inspired by a Henry Ford quote about paint on the Model T: “Any customer can have a car painted any color that he wants so long as it is black.”[36] Jokes aside, black generally formats code in ways that are pleasant, readable, and consistent.

--

--