PIP-Talk - Week 40

Every week going forward I plan to write a little about interesting modules/libraries available for Python.

The topic for this week is: “Cleaning” with Black, the “safe” code formatter for Python.

![logo](img src=“https://black.readthedocs.io/en/stable/_static/logo2-readme.png")

Why and What ?

  • Black is a code formatter that automatically adjusts and verifies your Python code.
  • Black’s formatting rules are a superset of PEP 8.
  • Simple “format” code-review, will not be needed anymore.
  • Formatting becomes transparent, and you could save time and mental energy :-)

If you choose to use Black, you get PEP 8 compliance for free, plus some other style choices that the Black team sees as helpful for making maintainable code.


How Black works - in three steps

  • Step-1. Parse the Python code.
  • Step-2. Apply formatting rules.
  • Step-3. Verify that the formated code result into same internal representation in Python.

Since there is (almost) nothing to configure, you are already prepared to format your code.


Get started

First of all, install black:

pip install black"

You could run black on a single file or a folder. There are several ways of operating the black tool once it is installed.

dry run - mode

In the dry run mode, black will only display code that will be needed to reformat. This mode is specially usefull for code reviews or when learning python.

black --check file_name.py

default mode

In the deafult mode, black will automatically apply the needed changes:

black file_name.py

interactive mode

There is also a “interactive” mode; where you can check a single line of code, to see what actions black would perform.

 black --code "user:str='nisse'"

diff mode

Finally there is a diff mode, which will do a dry run and display a traditional diff view, with the changes.

black --diff file_name.py


Links and resources