Back to Tutorials

Autoformat Python Code Using Black

What is PEP?

PEP 8 (Python Enhancement Proposal-8) is the official style guide for Python. It sets the standard for writing consistent and readable source code. However, manually adhering to PEP 8 can be tedious, especially in larger codebases. That's where Black comes in.

What is Black?

Black is a PEP 8-compliant opinionated formatter that adjusts the layout and structure of your Python code. It automatically rewrites code to conform to style rules. It focuses on code appearance and readability (e.g., line length, indentation, spacing, and wrapping).

How to Use Black?

1. Activate Your Virtual Environment

Before installing Black, you have to activate your virtual environment. A virtual environment helps isolate your project's dependencies from your global Python installation.

2. Install Black via pip

Once your virtual environment is active, download and install Black using pip by entering the following command in your terminal:

1
pip install Black

3. Flag codes to be ignored

You may want to flag the codes that Black should not reformat.

To ignore a single line of code, use # fmt: skip:

1
2
3
x = 1 # fmt: skip
y = 2
z = x + y

To ignore a block of code, start with # fmt: off and end with # fmt: on:

1
2
3
4
5
# fmt: off
x = 1
y = 2
z = x + y
# fmt: on

4. (Optional) Customize Black's configuration

You can use a configuration file called pyproject.toml to customize Black's behavior further. For more information, you may want to visit Black's official documentation.

As mentioned in their official documentation, Black is all about sensible defaults. They said that you do not need to configure anything. They are really opinionated. Isn't it? 😉 Well, I took their advice and have not encountered any issues yet.

5. Format Files

Make sure to navigate to the correct directory before running the following code.

To format a single file:

1
black [file_name].py

To format the files in the entire directory:

1
black [directory_name]/

Sample Black's Formatting

Before formatting:

1
2
3
4
def messy_function(x,y):
  if x>y: print("X is greater than Y")
  else:
        print("Y is greater or equal to X")

After formatting:

1
2
3
4
5
def messy_function(x, y):
    if x > y:
        print("X is greater than Y")
    else:
        print("Y is greater or equal to X")