Last modified: Oct 14, 2026

Sort Python Imports Automatically with isort

Imports sit at the top of every Python file. They are the first thing you write and often the first thing that turns messy. A few quick additions and suddenly your import block is out of order.

isort solves this problem. It sorts imports automatically, groups them by type, and removes duplicates. You stop thinking about import order and start focusing on real logic.

This guide walks you through the whole process. You will learn how isort works, how to configure it, and how to run it without typing a single command by hand.

What isort Actually Does

isort is a Python utility that reformats your import statements. It splits them into sections and sorts each section alphabetically.

The default sections are standard library, third-party, and first-party. isort can also add a separate section for local application imports.

Beyond sorting, isort handles several small but annoying tasks. It merges duplicate imports, removes unused ones in some modes, and wraps long lines that exceed your limit.

The result is predictable code. Every file in your project follows the same import style, no matter who wrote it.

If you have not set it up yet, start with this guide on how to install isort in Python. Then come back here for the automation part.

Before and After: A Quick Example

Seeing the difference makes the tool easier to understand. Here is a typical messy import block.

 import sys import requests import os from mypackage import utils import json from mypackage.models import User import requests 

This block has mixed sections, duplicates, and no clear order. Now run isort on the file.

 isort example.py 

The same file now looks like this.

 import json import os import sys import requests from mypackage import utils from mypackage.models import User 

Standard library imports come first. Third-party packages follow. Local imports sit at the bottom. The duplicate requests import is gone.

That is the core value of isort. One command turns chaos into a clean, readable structure.

Running isort on a Whole Project

You rarely sort one file at a time. isort can walk an entire directory tree and fix every Python file it finds.

 isort . 

This command sorts every file in the current directory and all subdirectories. Directories like venv, .git, and build are skipped by default.

You can also point isort at a specific folder.

 isort src tests 

If you only want to see what would change, use the diff flag. Nothing is written to disk.

 isort . --diff 

The output looks like a standard patch file. You can review every change before applying it.

For CI pipelines, use the check flag. It exits with a non-zero code when imports are unsorted, which fails the build.

 isort . --check --diff 

This is the safest way to enforce import order across a team. Nobody can merge unsorted imports.

Configuring isort for Your Project

Default settings work, but most projects need a few tweaks. isort reads configuration from several files, including pyproject.toml, .isort.cfg, setup.cfg, and tox.ini.

The modern choice is pyproject.toml. Here is a solid starting configuration.

 [tool.isort] profile = "black" line_length = 88 known_first_party = ["myapp"] src_paths = ["src", "tests"] skip = ["migrations", ".venv"] 

The profile option is the most important line. Setting it to black makes isort fully compatible with the Black formatter. Without it, the two tools fight over your code.

The known_first_party option tells isort which packages belong to your project. This prevents your own modules from being sorted into the third-party block.

The src_paths option defines where your source code lives. isort uses it to resolve local imports correctly.

Using isort as a Python Library

You do not have to run isort from the shell. It exposes a Python API that you can call from your own scripts.

 import isort # Sort a single file in place isort.file("my_script.py") # Sort a string and get the result back source = "import sys\nimport os\n" sorted_source = isort.code(source) print(sorted_source) # Check if a string is already sorted is_sorted = isort.check_code(source) print(is_sorted) 

The output confirms both calls worked as expected.

 import os import sys False 

The isort.file() method rewrites a file on disk. The isort.code() method returns a sorted string instead. The isort.check_code() method returns a boolean without modifying anything.

This is useful in code generators. You can sort imports right before writing a generated file, so the output is always clean.

If your project also produces reports or documents, you might pair this with a library that helps you generate PDFs with ReportLab in a Python guide. Sorted imports keep those scripts readable as they grow.

Automating isort with Pre-commit

Running isort manually is easy to forget. Pre-commit hooks solve that problem. They run isort automatically before every commit.

First, install pre-commit itself.

 pip install pre-commit 

Next, create a file named .pre-commit-config.yaml in your project root.

 repos: - repo: https://github.com/PyCQA/isort rev: 6.0.1 hooks: - id: isort args: ["--profile", "black"] 

Now install the hook into your local repository.

 pre-commit install 

From this point on, every git commit triggers isort. If imports are unsorted, isort fixes them and the commit is blocked once so you can review the change.

This is the closest thing to true automation. You never run isort by hand again.

Automating isort in CI

Pre-commit protects your local machine. CI protects the shared repository. Both are worth having.

Add a step to your pipeline that checks import order. Here is a GitHub Actions example.

 name: Lint on: [push, pull_request] jobs: isort: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.12" - run: pip install isort - run: isort . --check --diff 

The final step fails the job if any file has unsorted imports. Contributors see exactly which lines need fixing.

This pattern works with GitLab CI, CircleCI, and Jenkins too. Only the syntax changes.

Combining isort with Black

Black formats code. isort formats imports. They overlap, and that overlap causes conflicts when configured poorly.

The fix is simple. Set profile = "black" in your isort configuration and add isort before Black in your pipeline.

 - repo: https://github.com/PyCQA/isort rev: 6.0.1 hooks: - id: isort - repo: https://github.com/psf/black rev: 24.10.0 hooks: - id: black 

Order matters here. isort sorts the imports first. Black then reformats the rest without touching import order.

When both tools agree, your diffs stay small and your reviews stay fast. That is the entire goal.

Handling Common Problems

Imports keep getting reordered on every run. This usually means two tools disagree. Check that the Black profile is set and that Black runs after isort.

isort skips a file you care about. The file may be inside a skipped directory. Check your skip setting and any .gitignore rules that isort respects by default.

Local imports land in the third-party section. Add your package name to known_first_party. This is the most common configuration mistake.

Long import lines wrap differently than expected. Adjust line_length and make sure it matches your Black setting. A mismatch causes constant churn.

isort is slow on a large repo. Use the --jobs flag to run in parallel. On big monorepos this cuts runtime significantly.

If you work with scheduled jobs or background workers, clean imports matter even more. Pipelines that schedule Python tasks with Airflow often span dozens of files, and consistent imports make those DAGs easier to debug when something breaks at 3 a.m.

Tips for Teams

Agree on one configuration file and commit it. Arguments about import order disappear once the tool decides.

Run isort in CI, not just locally. Local hooks can be bypassed with a flag. CI cannot.

Keep isort updated. New releases support new Python syntax and fix edge cases in import parsing.

Do not mix manual edits with automated ones. If isort sorts your imports, stop reordering them by hand.

Finally, document the setup in your README. New contributors should know that imports are handled automatically, so they do not waste time formatting them.

Conclusion

Sorting Python imports by hand is a waste of time. isort removes that chore completely.

Install it, add a config file, and wire it into pre-commit. Then add a CI check so nothing slips through.

Within a week you will forget imports were ever a problem. Your diffs get smaller, your reviews get faster, and your codebase stays consistent.

That is a small change with a surprisingly large payoff. Set it up once and let it run.