What's the correct way to sort Python `import x` and `from x import y` statements?

Learn what's the correct way to sort python import x and from x import y statements? with practical examples, diagrams, and best practices. Covers python, coding-style, python-import developmen...

Mastering Python Imports: Sorting for Readability and PEP 8 Compliance

Hero image for What's the correct way to sort Python `import x` and `from x import y` statements?

Learn the correct way to sort Python import x and from x import y statements to improve code readability and adhere to PEP 8 guidelines. This guide covers standard practices, tools, and best strategies.

Organizing your Python import statements might seem like a minor detail, but it's a crucial aspect of writing clean, readable, and maintainable code. Adhering to a consistent import order, as outlined by PEP 8, makes it easier for developers (including your future self) to quickly understand a module's dependencies and reduces merge conflicts. This article will guide you through the standard practices for sorting imports, explain the rationale behind them, and introduce tools that can automate this process.

The PEP 8 Standard for Import Order

PEP 8, the style guide for Python code, provides clear recommendations for how import statements should be structured and ordered. The primary goal is to group imports logically, making the top of your Python file a clear declaration of its external dependencies. The standard dictates three main groups, separated by blank lines, and within each group, imports should be sorted alphabetically.

flowchart TD
    A[Start of File] --> B["Standard Library Imports (e.g., `os`, `sys`)"]
    B --> C["Third-Party Library Imports (e.g., `requests`, `numpy`)"]
    C --> D["Local Application/Project Imports (e.g., `from . import models`)"]
    D --> E[End of Imports]

PEP 8 Recommended Import Order Flow

Let's break down these three groups:

1. Standard Library Imports

These are modules that come bundled with Python itself. Examples include os, sys, math, json, datetime, etc. These should always come first.

2. Third-Party Library Imports

These are modules you've installed from external sources, typically via pip. Examples include requests, numpy, pandas, Django, Flask, etc. These come after standard library imports.

3. Local Application/Project Imports

These are modules that are part of your own project or application. They often use relative imports (e.g., from . import views) or absolute imports within your project's structure. These should be placed last.

Alphabetical Sorting Within Groups

Once you've grouped your imports, the next step is to sort them alphabetically within each group. This applies to both import x and from x import y statements. For from x import y statements, the primary sort key is x, and the secondary sort key is y.

# Standard library imports
import os
import sys
from collections import defaultdict

# Third-party imports
import numpy as np
import requests
from flask import Flask, jsonify

# Local application/library specific imports
from . import models
from my_project.utils import helper_function
from my_project.views import user_view

Example of correctly sorted Python import statements

Automating Import Sorting with isort

Manually sorting imports can be tedious and error-prone. Fortunately, tools exist to automate this process, ensuring consistent adherence to PEP 8 and other configurable styles. The most popular tool for this is isort.

isort automatically sorts your imports alphabetically and separates them into sections. It's highly configurable and can integrate with various editors and CI/CD pipelines.

# Install isort
pip install isort

# Run isort on a single file
isort my_module.py

# Run isort on an entire directory
isort my_project_directory/

Basic usage of the isort command-line tool

Advanced isort Configuration

isort allows for extensive customization through configuration files (e.g., pyproject.toml, setup.cfg, isort.cfg). You can define custom sections, specify known third-party libraries, and set line length limits.

# setup.cfg or .isort.cfg
[isort]
profile=black
known_first_party=my_project
known_third_party=requests,numpy,flask
multi_line_output=3
include_trailing_comma=True
force_grid_wrap=0
use_parentheses=True
ensure_newline_before_comments=True
line_length=88

Example isort configuration in setup.cfg

In this configuration:

  • profile=black tells isort to use the Black code formatter's style for imports.
  • known_first_party helps isort correctly identify your project's modules.
  • known_third_party explicitly lists third-party libraries, which can be useful for disambiguation.
  • Other settings control formatting details like line length and multi-line output.