isort + autopep8 Reference: Python Import Sorting | Web Formatter Blog

isort + autopep8 Reference: Python Import Sorting
A comprehensive guide to organizing imports and formatting Python code using isort and autopep8.
Introduction to Python Code Formatting
Python's readability is one of its most celebrated features, but maintaining consistent code style across projects and teams can be challenging. This is where code formatters like isort and autopep8 come in, helping developers adhere to Python's style guidelines with minimal effort.
In this comprehensive guide, we'll explore how to use isort for organizing imports and autopep8 for general code formatting, ensuring your Python code is clean, consistent, and compliant with PEP 8 standards.
Why Format Your Python Code?
Consistent code formatting offers numerous benefits beyond aesthetics:
- Improved readability: Well-formatted code is easier to scan and understand
- Reduced cognitive load: Developers can focus on logic rather than style variations
- Easier collaboration: Consistent style reduces friction in team environments
- Better code reviews: Reviewers can focus on substance rather than style
- PEP 8 compliance: Adherence to Python's official style guide
- Fewer bugs: Some formatting issues can lead to subtle bugs
Python's community has established clear style guidelines in{" "} PEP 8 , and tools like isort and autopep8 help automate adherence to these standards.
Understanding isort
isort is a Python utility that sorts imports alphabetically and automatically separates them into sections. It provides several key features:
- Import organization: Groups imports into standard library, third-party, and local
- Alphabetical sorting: Sorts imports alphabetically within each section
- Import combining: Combines imports from the same module
- Line length management: Handles line wrapping for long imports
- Customizable sections: Allows defining custom import sections
- Profile support: Includes profiles for popular frameworks like Django and Google
Meanwhile, autopep8 focuses on general code formatting according to PEP 8 guidelines, handling issues like:
- Indentation: Fixes inconsistent indentation
- Whitespace: Corrects spacing around operators, commas, etc.
- Line length: Wraps long lines
- Trailing whitespace: Removes unnecessary whitespace
- Blank lines: Normalizes blank lines between functions and classes
- Comments: Adjusts comment formatting
Installation
Installing isort
You can install isort using pip:
pip install isort
For projects using Poetry:
poetry add isort --dev
Installing autopep8
Similarly, install autopep8 with pip:
pip install autopep8
Or with Poetry:
poetry add autopep8 --dev
For convenience, you can install both tools together:
pip install isort autopep8
Basic Usage
Using isort
To sort imports in a single file:
isort example.py
To sort imports in all Python files in a directory recursively:
isort .
To check if files are properly sorted without modifying them:
isort --check-only --diff example.py
This will show a diff of changes that would be made without actually making them.
Using autopep8
To format a single file:
autopep8 --in-place example.py
To format a file with aggressive level 2 changes (recommended):
autopep8 --in-place --aggressive --aggressive example.py
To format all Python files in a directory recursively:
autopep8 --in-place --recursive .
To see changes without modifying files:
autopep8 --diff example.py
Configuration
isort Configuration
isort can be configured through several methods:
-
A
.isort.cfg
file -
An
[isort]
section insetup.cfg
-
An
[tool.isort]
section in{" "}pyproject.toml
(recommended)
Example configuration in pyproject.toml:
[tool.isort]
profile = "black"
line_length = 88
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
use_parentheses = true
ensure_newline_before_comments = true
skip = ["venv", ".env", ".venv", "env", "migrations"]
Common configuration options include:
-
profile
: Pre-defined settings (black, django, google, etc.) -
line_length
: Maximum line length -
multi_line_output
: How to format multi-line imports -
sections
: Define custom import sections -
known_third_party
: List of known third-party packages -
known_first_party
: List of known first-party packages
autopep8 Configuration
autopep8 can be configured through:
- Command-line arguments
-
A
setup.cfg
file -
A
tox.ini
file -
A
pyproject.toml
file
Example configuration in setup.cfg:
[tool:autopep8]
max_line_length = 88
aggressive = 2
exclude = venv/*,migrations/*
ignore = E203, W503
Key configuration options include:
-
max_line_length
: Maximum line length -
aggressive
: Level of aggressive fixes (0-2) -
exclude
: Patterns to exclude -
ignore
: Error codes to ignore -
select
: Error codes to select
Using Profiles
isort provides several pre-defined profiles to match popular formatting styles:
-
black
: Compatible with the Black formatter -
django
: Follows Django's import style -
google
: Follows Google's Python style guide -
pycharm
: Matches PyCharm's default style -
pep8
: Strictly follows PEP 8
To use a profile:
isort --profile black example.py
Or in configuration:
[tool.isort]
profile = "black"
Code Examples
Import Sorting Examples
Let's see isort in action with some examples:
Notice how isort:
-
Groups standard library imports first (
os
,{" "}sys
,datetime
,typing
) -
Then third-party imports (
numpy
,{" "}pandas
,requests
) - Then local imports (relative imports and project-specific imports)
- Alphabetically sorts within each section
-
Sorts imports from the same module (
typing
)
Code Formatting Examples
Now let's see autopep8 in action:
autopep8 has fixed several issues:
- Corrected spacing around function parameters and operators
- Fixed indentation
- Wrapped long docstring lines
- Added proper blank lines between class and methods
-
Changed
==True
tois True
and{" "}==None
tois None
- Fixed spacing in list comprehension
Editor Integration
Integrating isort and autopep8 with your editor provides real-time formatting feedback.
Visual Studio Code
For VS Code, install the Python extension and configure it:
- Install the{" "} Python extension
- Open settings (Ctrl+,) and add these configurations:
{
"python.formatting.provider": "autopep8",
"python.formatting.autopep8Args": ["--aggressive", "--aggressive"],
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
}
This will run autopep8 on save and organize imports with isort.
PyCharm
For PyCharm:
- Go to Settings/Preferences → Tools → External Tools
-
Add a new tool for isort:
- Name: isort
- Program: path to isort executable
- Arguments: $FilePath$
- Working directory: $ProjectFileDir$
-
Add another tool for autopep8:
- Name: autopep8
- Program: path to autopep8 executable
- Arguments: --in-place --aggressive --aggressive $FilePath$
- Working directory: $ProjectFileDir$
You can then run these tools from the Tools menu or assign keyboard shortcuts.
Vim and Neovim
For Vim/Neovim, you can use plugins like ALE or integrate with external commands:
" For ALE
let g:ale_fixers = {
\ 'python': ['isort', 'autopep8'],
\}
let g:ale_fix_on_save = 1
" Or using custom commands
autocmd FileType python nnoremap i :!isort %
autocmd FileType python nnoremap a :!autopep8 --in-place --aggressive --aggressive %
Automating Formatting
Pre-commit Hooks
You can use pre-commit hooks to ensure all committed code is properly formatted:
- Install pre-commit:
pip install pre-commit
-
Create a
.pre-commit-config.yaml
file:
repos:
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
name: isort (python)
- repo: https://github.com/pycqa/autopep8
rev: v2.0.2
hooks:
- id: autopep8
- Install the hooks:
pre-commit install
Now, every time you commit, your Python files will be automatically formatted.
CI/CD Integration
You can also check formatting in your CI/CD pipeline. Here's an example for GitHub Actions:
name: Python Linting
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.10'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install isort autopep8
- name: Check import sorting
run: |
isort --check --diff .
- name: Check code formatting
run: |
autopep8 --exit-code --diff --recursive .
This workflow will fail if any files aren't properly formatted, ensuring code quality standards are maintained.
Comparison with Other Tools
isort/autopep8 vs. Black
How do isort and autopep8 compare to Black, another popular Python formatter?
Feature | isort + autopep8 | Black |
---|---|---|
Philosophy | Configurable, follows PEP 8 | Opinionated, minimal configuration |
Configurability | Highly configurable | Limited configuration options |
Import sorting | isort handles this specifically | Basic sorting only |
Line length | Configurable (default: 79) | 88 characters (configurable) |
String quotes | Configurable | Double quotes by default |
The isort + autopep8 combination offers more flexibility, while Black provides a more opinionated, "just works" approach. Many teams use isort with Black instead of autopep8 for a comprehensive solution.
isort/autopep8 vs. YAPF
YAPF is another Python formatter with a different approach:
Feature | isort + autopep8 | YAPF |
---|---|---|
Approach | Fix specific issues | Reformats entire code |
Algorithm | Rule-based fixes | Clang-style formatter |
Style options | PEP 8 focused | Multiple style options (pep8, Google, etc.) |
Import handling | Specialized with isort | Basic formatting only |
YAPF is another Python formatter with a different approach: