Skip to content

unsorted-imports

Pythonstyleno fixdefault: offpython/ruff

Reports a block of imports that differs from the sorted layout. The sections are __future__, the standard library, third party, first party and relative imports, with a blank line between them and after the block (two before a definition at module level). Within a section import x comes before from x import y, names are in natural order without regard to case, and members are ordered as constants, classes, then the rest. One statement is written for each module, and a from import over line_width columns (88) is wrapped in parentheses, one member to a line. The options sections and force_sort_within_sections change the order. A folder or file next to the file, in the project root or in its src folder, is first party.

Imports in one fixed order show at a glance which dependencies a file has, a new import has one place, and merge conflicts in the import block are rare. An order that a tool can check needs no discussion in a review.

To fix, sort the block by hand or with an import sorter.

Reported
...
class A:
...
import os as os
...
import sys
...
import functools
...
pass
import subprocess
...
a = b = "x"
...
...
import re
...
python:
lint:
rules:
unsorted-imports:
level: warn # off (default), warn, error
options:
sections: ["future","standard-library","third-party","first-party","local-folder"]
force_sort_within_sections: false
line_width: 88
Option Type Default Description
sections list ["future","standard-library","third-party","first-party","local-folder"] The sections of the block in the order they are written; a section left out comes last.
force_sort_within_sections bool false Sort import x and from x import y together by module instead of the plain imports first.
line_width int 88 A from import over this many columns is wrapped in parentheses, one member to a line.

Enabled by the presets: python/ruff.

Suppress one line with sudsy-disable-next-line unsorted-imports in a comment of the file’s language.

The same check in other tools; Sudsy reports what each upstream rule reports.

Tool Rule Match
ruff I001 full