In the following article, you will learn about the importance of code formatting, Black formatter, the history of Black on git, its major contributors. You will also learn how to integrate Black to popular code editors and use Black in pre-commit hooks.
Writing efficient and effective code is a required skill for any programmer/developer. However, one’s task doesn’t end after ensuring that their code is running accordingly. Proper formatting of the code is equally necessary.
Often, novice developers overlook formatting and, ultimately, readability. Readability is not a concern in small programs or projects where lines of code are few. In large projects, it will become a nightmare for the team members without proper formatting.
Python’s PEP-8
PEP-8(Python Enhancement Proposal 8) is a list of guidelines and best practices for writing effective Python code. Written by Guido van Rossum, Barry Warsaw, and Nick Coghlan and aimed to make python codes consistent and readable.
So you might ask, will following python’s pep-8 guide solve the problem? The answer would be yes and no. Let’s elaborate on this with an example.
PEP-8 has guidelines for creating a list. Let’s look at them.
# first way
naruto_characters = ['sasuke', 'itachi', 'kakashi', 'hashirama', 'madara', 'orochimaru']
# another acceptable way
naruto_characters = [
'sasuke', 'itachi',
'kakashi', 'hashirama',
'madara', 'orochimaru'
]
# yet another acceptable way
naruto_characters = [
'sasuke',
'itachi',
'kakashi',
'hashirama',
'madara',
'orochimaru'
]
All the above ways are acceptable according to the PEP-8 guidelines. It is important to realize if you are in a team where each person uses a different style then there won’t be consistency in the codebase. Moreover, it might even lead to an argument trying to prove which method is the best or more pythonic than the other.
The bottom line is that in large projects, there should be consistency in formatting, which in turn would lead to better readability. How can we ensure that each team member adheres to proper formatting?
Introducing Black Git Repository
The answer is Black, a third-party formatter.
“Black is the uncompromising Python code formatter. By using it, you agree to cede control over minutiae of hand-formatting. You will save time and mental energy for more important matters.”
From documentation of Black
Black follows PEP-8 guidelines staunchly. In other words it doesn’t make any compromises. It does its job quickly and effectively, increasing readability and maintaining overall consistency in the code.
Black is used by many popular open-source projects like – pytest, Pyramid, Django, SQLAlchemy, Poetry, PyPA applications (Warehouse, Bandersnatch, Pipenv, virtualenv), pandas, to name a few.
The following organizations use Black: Facebook, Dropbox, KeepTruckin, Mozilla, Quora, Duolingo, QuantumBlack, Tesla.
Note: You can try out Black formatter at the black playground and also read about Black code style from here.
History of Black development on Git
The development of Black formatter on git started in the year 2018, described as “The uncompromising Python code formatter”. The first version was in the alpha stage. In the alpha stage, the program is tested by the developer using white-box techniques.
Here are some major changes in the Black formatter’s development on git.
Jupyter notebook support was added in version 21.12b0. This version fully supported python’s version 3.10.
The first stable release of Black on git is 22.1.0. All the versions before this were either in alpha or beta stages. In version 22.1.0, support for python2 has been discontinued.
Top contributers of Black on Git
The creator of Black is Łukasz Langa. He is a CPython Developer in Residence and Python 3.8, 3.9 release manager.
At the time of publishing of this article, there are currently 302 developers working together to improve, update and add new features to Black formatter on git. Here are some top contributors.
- Łukasz Langa
- Richard Si
- Zsolt Dollenstein
- Jelle Zijlstra
- Cooper Lees
- Hugo van Kemenade
- Batuhan Taskaya
- Marco Edward Gorelli
Installation
Installation of Black is pretty straightforward.
Installing Black using pip
pip install black
Installing Black from Git
If you want to want the latest version of Black, then you can run the following command.
pip install git+https://github.com/psf/black
Using Black Python formatter
Now that Black is installed in your system, let’s get familiar with its works.
Formatting a single .py file
Syntax: black <filename>
We have created a py script named test.py and as you can see, it is badly formatted. Let’s format it using Black.
import random
naruto_characters = [
'sasuke',
'itachi',
'kakashi', 'hashirama',
'madara',
'orochimaru'
]
def character_selected(char_list:list):
character = random.choice(char_list)
print(f"Hello, {character}")
black test.py
Code below is the reformatted code by Black.
import random
naruto_characters = ["sasuke", "itachi", "kakashi", "hashirama", "madara", "orochimaru"]
def character_selected(char_list: list):
character = random.choice(char_list)
print(f"Hello, {character}")
Formatting multiple .py files stored in a folder
Syntax: black <foldername>\
Black python formatter can easily reformat multiple python files stored inside a folder. Let’s look at how we can do so.
We have multiple python files stored in a folder named Sorting, which is needed to be reformatted.
black Sorting\
Black Git Version Control Integration
Integrating Black to version control will save time and will remove all the hassle of remembering to reformat your code before committing it to a repository. Git hooks run before every commit. We can simply add Black to the pre-commit configuration, then Black will reformat our code before every commit.
Let’s look at how we can achieve this before that install pre-commit using pip install pre-commit
.
#unformatted code
from collections import deque
graph = {"a": ["c", "b"],
"b": ["d"],
"c": ["e"], "d": ["f"],
"e": [], "f": []}
def bfs(graph, source):
queue = deque()
queue.append(source)
while len(queue) > 0:
current = queue.popleft()
print(current)
for neighbour in graph[current]:
queue.append(neighbour)
bfs(graph, "a")
- Firstly, create a folder named test_dir which contains unformatted test.py.
- Intialize it using
git init
command. - Then create a file named .pre-commit-config.yaml and paste the following content inside it.
repos:
- repo: https://github.com/ambv/black
rev: 21.9b0
hooks:
- id: black
language: python
types: [python]
- After that run
pre-commit install
in the terminal.
- This will create a pre-commit file in the .git hooks folder.
- Then add files for commiting and commit it using some message.
- Note: Since black has made changes to the test.py file, you will have to add files again and commit.
- The last step is to push the files to github.
Adding Black to VSCode
In order to add Black Python formatter to the vs code you will need to follow these steps:
- Make sure you have Black installed on you system.
- Open vscode extensions and install python extension.
- Once done with that, open settings and then open settings.json file.
- Add the lines below in the settings.json and then save it.
- Check path of Black using
which black
and paste against the"python.formatting.blackPath"
.
"python.formatting.provider": "black",
"python.formatting.blackPath": "/home/<user_name>/.local/bin/black",
"editor.formatOnSave": false,
"[python]": {
"editor.formatOnSave": true,
},
Voila, you have successfully added Black to the vs code editor. On using Ctrl + S, Black will format your python script.
Adding Black to Jupyter notebook
In order to add Black Python formatter to the jupyter notebook you will need to follow these steps:
- Firstly run these commands, simply paste them in the terminal and hit enter.
jupyter nbextension install https://github.com/drillan/jupyter-black/archive/master.zip --user
jupyter nbextension enable jupyter-black-master/jupyter-black
- Now, when you will run any jupyter notebook you will see Black button in the header section.
Now with Black installed in your jupyter notebook you can easily format code. Simply click on the cell that is needed to be formatted and then click on the Black button.
FAQs on Black Formatter for Python
Black follows PEP-8 guidelines staunchly in other words it doesn’t make any compromises. It does its job quickly and effectively hence, increasing readability and maintaining overall consistency in the code.
Flake-8 only suggests changes that should be made to make our code PEP-8 compliant while Black is the uncompromising Python code formatter, does all the formatting automatically in accordance with PEP-8.
Conclusion
Black Python formatter is a very useful library that not only saves us time but also makes our code consistent and readable. Moreover, we can also integrate Black with code editors and git version control.
Mike Bayer, the author of SQLAlchemy describes it best – “I can’t think of any single tool in my entire programming career that has given me a bigger productivity increase by its introduction. I can now do refactorings in about 1% of the keystrokes that it would have taken me previously when we had no way for code to format itself”.