The Python programing language is often praised for its simple syntax. In fact the language recognizes that code is read much more often than it is written. Black is a tool that automatically formats your Python source code making it uniform and compliant to the PEP-8 style guide.
How to install Black on Fedora
Installing Black on Fedora is quite simple. Black is maintained in the official repositories.
$ sudo dnf install python3-black
Black is a command line tool and therefore it is run from the terminal.
$ black --help
Format your Python code with Black
Using Black to format a Python code base is straight forward.
$ black myfile.py All done! ✨ 🍰 ✨ 1 file left unchanged. $ black path_to_my_python_project/ All done! ✨ 🍰 ✨ 165 files reformatted, 24 files left unchanged.
By default Black allows 88 characters per line, meaning that the code will be reformatted to fit within 88 characters per line. It is possible to change this to a custom value, for example :
$ black --line-length 100 my_python_file.py
This will set the line length to allow 100 characters.
Run Black as part of a CI pipeline
Black really shines when it is integrated with other tools, like a continuous integration pipeline.
The –check option allows to verify if any files need to be reformatted. This is useful to run as a CI test to ensure all your code is formatted in consistent manner.
$ black --check myfile.py would reformat myfile.py All done! 💥 💔 💥 1 file would be reformatted.
Integrate Black with your code editor
Running Black during the continuous integration tests is a great way to keep the code base correctly formatted. But developers really wants to forget about formatting and have the tool managing it for them.
Most of the popular code editors support Black. It allows developers to run the format tool every time a file is saved. The official documentation details the configuration needed for each editor.
Black is a must-have tool in the Python developer toolbox and is easily available on Fedora.