Open In App

Introduction to Python Black Module

Last Updated : 13 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Python, being a language known for its readability and simplicity, offers several tools to help developers adhere to these principles. One such tool is Black, an uncompromising code formatter for Python. In this article, we will delve into the Black module, exploring what it is, how it works, and why it's a valuable addition to our Python development toolkit.

What is Black in Python?

Black is an open-source Python code formatter that automatically formats our Python code according to the PEP 8 style guide. Unlike traditional linters that only highlight style issues, Black takes a more assertive approach by reformatting our code to comply with PEP 8, the style guide for Python code, without needing manual intervention.

Why Use Black?

  • Consistency: Black enforces a consistent coding style across our entire codebase. This is particularly useful in teams where different developers might have different coding styles.
  • Simplicity: By using Black, we don't have to spend time debating code style issues during code reviews. Black handles all the formatting, allowing us to focus on the actual functionality of the code.
  • Automation: Black can be easily integrated into our development workflow, whether we're working on a personal project or in a larger team. It can be run as a pre-commit hook, ensuring that all code is formatted before being committed to version control.
  • Speed: Black is optimized for speed. It can format large codebases quickly and efficiently, making it a practical tool for both small scripts and large applications.

Installing Black

We can install Black via pip, the Python package manager. Open our terminal or command prompt and execute the following command:

pip install black

The above command will download the latest version of Black in our Python environment.

Verify Installation

Once installed, to verify that Black is correctly installed, We can check its version. Within our terminal, we can run the following command in the bash shell:

black --version

We should see the version of Black installed pop into view, ready for action.

Basic Usage of Black

Black is incredibly easy to use. To format a Python file, navigate to the directory containing the file in our terminal and run:

1. Format a Single File

To format a single Python file with Black, all we need to do is provide the path to the file. So if we have a file called example.py then to format that we would run:

exmaple.py

Screenshot-2024-09-13-121425
A python file with unformatted code
black example.py

Black will format the file in-place, making indentation, line length and other style changes according to its rules.

Output:

Screenshot-2024-09-13-121440
Format single file using black

2. Format Multiple Files

To format multiple files or even whole projects, we can provide a directory or multiple paths to Black:

black file1.py file2.py

To format all Python files in the current directory and subdirectories, use:

black .

Black will recursively format all files in .py format.

3. Checking Files for Formatting

If we only want to check if a file or directory would be reformatted without actually doing the formatting, we have the option --check: this will exit with the code 1 if there's anything that would be changed, and 0 otherwise. This can be used in Continuous Integration pipelines.

black --check example.py

Output:

Screenshot-2024-09-13-121744
Checking files for formatting using Black

If the file is already well formatted we get a message that we don't need to make any changes. Otherwise, Black will give us suggestions.

4. Change Number of Characters per Line

By default Black limits line length to 88 characters; more relaxed than what is advised by PEP 8. If we'd like a different maximum line length we can pass that with the --line-length option. For example, to set it to 100 characters:

black --line-length 100 example.py

This will adjust Black's formatting to wrap lines at 100 characters instead of 88.

How to Use Black in Jupyter Notebook

Black can also be used to format code within Jupyter Notebooks. Here's how to integrate it:

Install nb_black

First, install the nb_black extension, which allows Black to be used in Jupyter notebooks:

pip install nb_black

Enable Black in Jupyter Notebook

Once installed, we need to load the Black extension in our Jupyter Notebook:

Python
%load_ext nb_black


Now, every time we run a cell, Black will automatically format the Python code within that cell according to its style rules.

Example:

Example 1: Formatting a Single File

file
Before using black

After running Black:

black example.py

The file will be formatted as:

file
After using black

Example 2: Formatting Multiple Files

QSEDWRFETGHJ
file1.py before formatting
file
file2.py before formatting

If we want to format two files need formatting without actually changing them, we can use:

black --check file1.py file2.py

After formatting results:

file
Formatted file1.py
file
Formatted file2.py

If either of the files is not formatted according to Black’s style, the command will suggest changes.

Example 3 : Checking Files for Formatting

file1.py

QSEDWRFETGHJ
file1.py

File2.py

file
file2.py

Command to check for formatting

black --check file1.py file2.py

If file is not formatted then returns:

would reformat file1.py
would reformat file2.py
2 files would be reformatted.

If files are already formatted then returns:

All done! 
2 files would be left unchanged.

If file needs formatting then run this command

black file1.py file2.py
file
Formatted file1.py
file
Formatted file2.py

Example 4: Changing Line Length

Using a higher limit, such as 100 characters per line, keeps the function in one line:

black --line-length 100 example.py

Before Black reformats a file with a longer line length, the code might look like this:

file
Before Black reformats a file with a longer line length

Running Black with the default 88-character limit might reformat the code like this:

file
After Running Black with the default 88-character limit

Formatting a Small Python Project

Let's assume we have a small Python project that calculates the area of a circle.

Python
import math

def calc_area(radius):return math.pi * radius ** 2

def display_area(radius):
  area = calc_area(radius)
  print(f"The area of a circle with radius {radius} is {area}")

display_area(5)

This code works fine, but it's not well-formatted. Let's use Black to format it.

black circle_area.py

Output:

Screenshot-2024-09-13-165803
Format a Python Script

Conclusion

Black is a really good formatting tool for any Python developer that keeps code style consistent without manual intrusions. It automates formatting so a developer can spend more time implementing the logic or functionality rather than caring about style. Working on a small script or huge project, the inclusion of Black in our workflow will mean that our code is standardized and clean. Compatible with Jupyter Notebooks and flexible in terms of options such as line length, Black is ready for action within a wide variety of coding environments.


Next Article
Article Tags :
Practice Tags :

Similar Reads