Python Code Style (PEP8) and Formatters (black, isort)


Table of Contents

  • Introduction
  • What is PEP8 and Why Does It Matter?
  • Key Guidelines from PEP8
  • Common Violations and Mistakes
  • Introduction to Code Formatters
  • Overview of black Formatter
  • Overview of isort Tool
  • How to Integrate black and isort into Your Workflow
  • Best Practices for Maintaining Code Quality
  • Conclusion

Introduction

As Python developers, we often focus on writing functional code, but writing readable, consistent, and maintainable code is equally important.
Python embraces the philosophy that “code is read more often than it is written”, and to enforce this, the community follows a standard code style guide known as PEP8.

In this article, you will learn not only about PEP8 and its key rules but also how modern code formatters like black and isort can automate code styling, saving time and improving codebase quality.


What is PEP8 and Why Does It Matter?

PEP8 stands for Python Enhancement Proposal 8.
It is the official style guide for Python code, originally authored by Guido van Rossum (Python’s creator) and others.

The goals of PEP8 are:

  • To improve the readability of Python code.
  • To establish a consistent coding style across the Python community.
  • To encourage best practices that lead to better software maintainability.

Ignoring coding style in collaborative projects can result in messy codebases, endless debates over formatting, and ultimately wasted development hours.

Following PEP8 allows developers to:

  • Easily understand each other’s code.
  • Reduce cognitive load.
  • Catch bugs more easily through uniform formatting.

Key Guidelines from PEP8

Here are some of the essential guidelines outlined in PEP8:

1. Indentation

Use 4 spaces per indentation level. Never use tabs.

def my_function():
print("Hello, world!")

2. Line Length

Limit all lines to a maximum of 79 characters. For docstrings or comments, aim for 72 characters.

3. Blank Lines

Separate top-level functions and class definitions with two blank lines.

def function_one():
pass


def function_two():
pass

4. Imports

  • Imports should usually be on separate lines.
  • Group imports in the following order:
    1. Standard library imports
    2. Related third-party imports
    3. Local application/library-specific imports
  • Use absolute imports where possible.

Example:

import os
import sys

import requests

from mypackage import mymodule

5. Spaces in Expressions and Statements

Avoid extraneous spaces.

Bad:

x = 1 * ( 2 + 3 )

Good:

x = 1 * (2 + 3)

6. Naming Conventions

  • Variables, functions: lowercase_with_underscores
  • Classes: CapWords
  • Constants: UPPERCASE_WITH_UNDERSCORES

Example:

def calculate_area():
pass

class Circle:
pass

MAX_SIZE = 100

Common Violations and Mistakes

  • Mixing tabs and spaces for indentation
  • Not following proper import order
  • Writing excessively long lines
  • Using inconsistent naming conventions
  • Adding too many or too few blank lines
  • Forgetting to add whitespace around operators

Recognizing these early can prevent problems later, especially in larger, more complex projects.


Introduction to Code Formatters

Manually fixing formatting issues can be tedious and error-prone.
Automated code formatters solve this problem by automatically adjusting code to conform to standards like PEP8.

Benefits of using code formatters:

  • Save time and reduce manual work.
  • Maintain consistent style across teams.
  • Focus more on business logic rather than formatting disputes.

The two most popular tools for Python code formatting are black and isort.


Overview of black Formatter

black is a powerful opinionated code formatter for Python.
It automatically reformats Python code to meet PEP8 guidelines with minimal configuration.

Key features of black:

  • Opinionated: You have few configuration options, ensuring everyone’s code looks the same.
  • Deterministic: Given the same input, black always produces the same output.
  • Focus on readability: It optimizes code formatting for maximum clarity.

Installation

pip install black

Basic Usage

black your_script.py

It will reformat your file in place.
You can also format entire directories:

black your_project/

Example

Before black:

def add(a,b):return a+b

After black:

def add(a, b):
return a + b

As you can see, it applies standard spacing, line breaks, and more.


Overview of isort Tool

isort focuses specifically on sorting and organizing imports automatically.

It groups imports correctly (standard libraries first, then third-party, then local imports) and ensures they are ordered alphabetically within their groups.

Installation

pip install isort

Basic Usage

isort your_script.py

You can configure how strict or loose you want the sorting to be through a configuration file (like .isort.cfg or pyproject.toml).

Example

Before isort:

import requests
import os
import sys
from mypackage import utils

After isort:

import os
import sys

import requests

from mypackage import utils

How to Integrate black and isort into Your Workflow

You can integrate black and isort into:

  • Git hooks: Automatically format code before every commit.
  • CI/CD pipelines: Ensure style compliance during automated tests.
  • VSCode / PyCharm extensions: Auto-format code on save.

For Git hooks, you can use pre-commit:

pip install pre-commit
pre-commit install

.pre-commit-config.yaml:

repos:
- repo: https://github.com/psf/black
rev: stable
hooks:
- id: black
- repo: https://github.com/PyCQA/isort
rev: stable
hooks:
- id: isort

This ensures your code is always styled properly without manual intervention.


Best Practices for Maintaining Code Quality

  • Use black and isort together: Ensure full formatting and import sorting.
  • Run formatters early and often: Do not wait until the project is huge.
  • Standardize across the team: Everyone should use the same settings.
  • Include style checks in CI: Automate enforcement of code style rules.
  • Prefer automatic over manual fixes: Let tools do the boring work.

Consistency, not personal preference, should drive formatting decisions.


Conclusion

Adhering to PEP8 and using automated tools like black and isort will help you write professional-grade Python code.
They ensure that your codebase remains clean, readable, and maintainable — a must-have for modern Python development, especially in collaborative environments.

Investing a little time to master these tools will pay significant dividends in improved project quality and developer productivity over time.

Syskoolhttps://syskool.com/
Articles are written and edited by the Syskool Staffs.