Introduction to Python Black Module
Last Updated :
13 Sep, 2024
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
A python file with unformatted codeblack example.py
Black will format the file in-place, making indentation, line length and other style changes according to its rules.
Output:
Format single file using black2. 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:
Checking files for formatting using BlackIf 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
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
Before using blackAfter running Black:
black example.py
The file will be formatted as:
After using blackExample 2: Formatting Multiple Files
file1.py before formatting
file2.py before formattingIf we want to format two files need formatting without actually changing them, we can use:
black --check file1.py file2.py
After formatting results:
Formatted file1.py
Formatted file2.pyIf 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
file1.pyFile2.py
file2.pyCommand 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
Formatted file1.py
Formatted file2.pyExample 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:
Before Black reformats a file with a longer line lengthRunning Black with the default 88-character limit might reformat the code like this:
After Running Black with the default 88-character limitFormatting 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:
Format a Python ScriptConclusion
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.
Similar Reads
Introduction to Python Colorama
In Python, when it comes to terminal output, the default experience can be somewhat monotonousâtext is usually displayed in a single color, which can make it challenging to distinguish between different types of output. This is where Colorama comes into play. Colorama is a Python library that simpli
6 min read
Introduction to Python3
Python is a high-level general-purpose programming language. Python programs generally are smaller than other programming languages like Java. Programmers have to type relatively less and indentation requirements of the language make them readable all the time. Note: For more information, refer to P
3 min read
Introduction to Python Typing-Extensions Module
The typing-extensions module provides backports of the latest typing features to ensure that developers working with older versions of Python can still leverage these advanced tools. This module acts as a bridge between future releases of Python and existing codebases, enabling us to stay up to date
8 min read
Built-in Modules in Python
Python is one of the most popular programming languages because of its vast collection of modules which make the work of developers easy and save time from writing the code for a particular task for their program. Python provides various types of modules which include Python built-in modules and ext
9 min read
How to Install a Python Module?
A module is simply a file containing Python code. Functions, groups, and variables can all be described in a module. Runnable code can also be used in a module. What is a Python Module?A module can be imported by multiple programs for their application, hence a single code can be used by multiple pr
4 min read
Import module in Python
In Python, modules allow us to organize code into reusable files, making it easy to import and use functions, classes, and variables from other scripts. Importing a module in Python is similar to using #include in C/C++, providing access to pre-written code and built-in libraries. Pythonâs import st
3 min read
Getopt module in Python
The getopt module is a parser for command-line options based on the convention established by the Unix getopt() function. It is in general used for parsing an argument sequence such as sys.argv. In other words, this module helps scripts to parse command-line arguments in sys.argv. It works similar t
2 min read
How to create modules in Python 3 ?
Modules are simply python code having functions, classes, variables. Any python file with .py extension can be referenced as a module. Although there are some modules available through the python standard library which are installed through python installation, Other modules can be installed using t
4 min read
Introduction to Python Pydantic Library
In modern Python development, data validation and parsing are essential components of building robust and reliable applications. Whether we're developing APIs, working with configuration files, or handling data from various sources, ensuring that our data is correctly validated and parsed is crucial
7 min read
C Extension Module using Python
Writing a simple C extension module directly using Pythonâs extension API and no other tools. It is straightforward to make a handcrafted extension module for a simple C code. But first, we have to make sure that the C code has a proper header file. Code #1 : #include <math.h> extern int gcd(i
4 min read