How to sort Python imports with Ruff
⚠️
This guide assumes you have uv installed. If you haven’t installed uv yet, follow the installation instructions before proceeding.
This guide shows how to automatically organize and sort Python imports using ruff:
Sorting a Single File
To sort imports in a Python file called example.py
:
$ uvx ruff check --select I --fix example.py
This command:
- Uses the
--select I
flag to enable only import sorting rules - Applies fixes automatically with
--fix
- Targets the file
example.py
Sorting an Entire Directory
To sort imports across all Python files in the current directory and its subfolders:
$ uvx ruff check --select I --fix .
Using ruff in a Project
For ongoing import sorting in a project:
- Add ruff as a development dependency:
$ uv add --dev ruff
- Configure ruff in pyproject.toml:
[tool.ruff]
select = ["I"]
- Run import sorting with:
$ uv run ruff check --fix .
Last updated on