Sub topic 11
Sorting imports with Ruff
This chapter assumes you can run ruff check and ruff format, and that you can edit [tool.ruff.lint] in pyproject.toml. It covers the I rules, which sort and group imports in the same way as isort. You will see how Ruff classifies each import, how to tune that behavior, and the mistakes that most often make sorting seem broken.
Sorting is a lint rule, not a formatter feature
ruff format never reorders imports. Import sorting belongs to the linter, under the I prefix:
| Code | Name | What it reports |
|---|---|---|
| I001 | unsorted-imports | An import block is not sorted or grouped as configured |
| I002 | missing-required-import | A module listed in `required-imports` is absent from the file |
The default rule set does not include I. If you never select it, Ruff never sorts anything. Add it to the selected families:
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F", "I"]Then run the check and the fix:
ruff check --select I .
ruff check --select I --diff .
ruff check --select I --fix .
ruff format .The --diff flag prints what would change without writing files. Run the fix before the formatter, because the formatter then normalizes whatever layout the sorter produced.
What a sorted file looks like
Ruff splits imports into sections and separates each section with one blank line. This file is unsorted:
from shop.models import Order
import sys
import requests
from . import utils
import os
from collections import defaultdictAfter ruff check --select I --fix, it becomes:
import os
import sys
from collections import defaultdict
import requests
from shop.models import Order
from . import utilsThree things changed. The imports were grouped into sections. Within a section, plain import x statements come before from x import y statements. Each group is alphabetized.
How Ruff classifies an import
Ruff assigns every import to one of five default sections, in this order:
future:from __future__ import ...standard-library: modules shipped with Pythonthird-party: installed packages such asrequestsfirst-party: modules in your own projectlocal-folder: relative imports such asfrom . import utils
The standard-library check depends on your target-version. Ruff carries a list of stdlib module names per Python version, so a module that joined the standard library in a later release may be classed as third-party if your target is older.
First-party detection
Ruff decides whether a module is first-party by looking for it in the directories listed in the src setting. The default is the project root and a src directory. A layout like this works with no configuration:
project/
pyproject.toml
src/
shop/
models.pyIf your code lives elsewhere, say so explicitly:
[tool.ruff]
src = ["src", "services/api"]
[tool.ruff.lint.isort]
known-first-party = ["shop"]
known-third-party = ["pydantic"]known-first-party and known-third-party override detection for the names you list. Use them when the same code is linted from different working directories and detection gives different answers.
Common configuration options
All isort options live under [tool.ruff.lint.isort]. These are the ones you will use most:
| Option | Effect |
|---|---|
| `known-first-party` | Force these module names into the first-party section |
| `known-third-party` | Force these module names into the third-party section |
| `section-order` | Change the order of sections, or add custom ones |
| `force-sort-within-sections` | Sort `import x` and `from x import y` together by module name |
| `force-single-line` | Put each imported name on its own line |
| `combine-as-imports` | Merge `from x import a as b` with other imports from `x` |
| `lines-after-imports` | Number of blank lines after the import block |
| `required-imports` | Imports that must appear in every file (triggers I002) |
| `split-on-trailing-comma` | Keep a multi-line `from` import expanded if it has a trailing comma (default `true`) |
A configuration that adds a future import to every file and sorts by module name:
[tool.ruff.lint.isort]
force-sort-within-sections = true
combine-as-imports = true
known-first-party = ["shop"]
required-imports = ["from __future__ import annotations"]With required-imports, ruff check --select I --fix inserts the missing line at the top of each file. Run it on an existing codebase with care, because it edits every file that lacks the import.
Custom sections
Suppose your team has an internal package namespace acme that should sit between third-party and first-party code. Define a section and place it in the order:
[tool.ruff.lint.isort]
known-local-folder = ["acme_shared"]
section-order = [
"future",
"standard-library",
"third-party",
"first-party",
"local-folder",
]Use section-order to reorder the built-in names. Adding custom section names also requires entries in the sections table, so check the isort settings reference before inventing sections.
Sorting within a block
Ruff sorts each contiguous block of imports separately. A block ends at the first line that is not an import, a comment attached to an import, or a blank line followed by code. This has a practical consequence:
import sys
sys.path.insert(0, "vendor")
import legacy_module
import osRuff treats import sys and the two imports after the sys.path.insert call as separate blocks. It will not move os above the call. Imports after executable code also raise E402 if you select the E rules that cover it. Keep imports at the top, or mark deliberate exceptions.
Preventing a file or block from being sorted
Ruff honors isort's action comments:
# isort: skip_file# isort: off
import b
import a
# isort: onA single statement can carry # isort: skip. You can also suppress the rule with # noqa: I001 on the first line of the import block. Use these for imports whose order matters at runtime, such as a patch that must load before a library. Prefer a short comment that says why.
Per-file settings
Not every file wants identical import rules. Test files and __init__.py files are the usual exceptions:
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
"tests/**/*.py" = ["I001"]The first line ignores unused-import warnings in package initializers, which often re-export names. It does not turn off sorting there. Ignore I001 only for files where you accept manual ordering.
Interaction with the formatter
The sorter and the formatter agree about what a good import line looks like, with one caveat. Ruff's formatter does not collapse or split parenthesized imports on its own, but the sorter does. If a from import has a magic trailing comma, split-on-trailing-comma = true keeps it exploded onto one name per line. Setting the option to false lets the sorter collapse it back onto one line when it fits.
The practical rule is to run ruff check --fix and then ruff format. Running them in the other order is safe, but the second command may change lines the first one touched, which makes your commit diffs noisier. Running both in CI as checks, ruff check . and ruff format --check ., catches any file where either step was skipped.
Troubleshooting
- Nothing is sorted.
Iis not inselect. Checkruff check --show-settingsfor the effective rule list, or add the family withextend-select = ["I"]. - The first-party module lands in the third-party section. Ruff did not find it under
src. Setsrcorknown-first-party. - Local results differ from CI. The two environments run Ruff from different directories, or use different Ruff versions. Pin the version and set
srcexplicitly. - A fix is offered, but the file changes unexpectedly. Run
ruff check --select I --difffirst. Review diffs on files with comments between imports, because comments attached to an import move with it. - Stdlib modules appear third-party. Your
target-versionis older than the Python release that added the module.
Summary of the workflow
- Add
Itoselectin[tool.ruff.lint]. - Set
srcorknown-first-partyso your own modules are classified correctly. - Preview with
ruff check --select I --diff .. - Apply with
ruff check --select I --fix ., then runruff format .. - Keep deliberate exceptions local, with
# isort: offor# noqa: I001.
Exercise
Your project selects ["E4", "E7", "E9", "F"]. A teammate says ruff format . should be sorting imports but it is not. Give two changes that make imports sorted, and the order in which you run the commands.
Show answer
Ruff's formatter never sorts imports, and the I family is not selected. Add "I" to select (or use extend-select = ["I"]). Then run ruff check --select I --fix . first, followed by ruff format .. Running ruff check --fix . after adding I to the config also works, since the fix applies the sorter along with the other safe fixes.
Exercise
Ruff puts from billing import invoice in the third-party section, but billing is a package in your repository under services/billing_app/billing. How do you fix it, and why does the problem not show up on every machine?
Show answer
Add the directory that contains the package to src (for example src = [".", "services/billing_app"]), or list the name in [tool.ruff.lint.isort] known-first-party = ["billing"]. Detection depends on where Ruff finds the module relative to src, and that depends on the working directory and configuration it loads. A machine that runs from a different directory, or has a package of the same name installed in its environment, can classify it differently. Setting src or known-first-party explicitly removes that dependence.