Skip to content

Sorting Imports with Ruff

Replacing isort in Python projects without configuration files

Problem Statement

When using Ruff for Python code formatting with ruff format ., you might notice it doesn't sort imports like the isort tool. This presents a challenge when you want to cleanly organize imports in small projects that lack configuration files such as pyproject.toml.

Solution

Ruff handles import sorting through its linter (ruff check) rather than its formatter. For isort-equivalent functionality, follow this two-step process:

  1. Use ruff check with specific import-related rules
  2. Apply formatting with ruff format after imports are sorted

Context

Ruff manages import sorting separately from code formatting. The I rule category corresponds to isort functionality (RFC: Import Sorting).

bash
# Sort imports (isort replacement)
ruff check --select I --fix .

# Format code with sorted imports
ruff format .

Key details

  • --select I: Targets all import-sorting rules
  • --fix: Automatically corrects violations
  • .: Processes current directory recursively

Advanced Usage

Single Command Execution

Chain both operations for convenience (Unix-like shells):

bash
ruff check --select I --fix . && ruff format .

Configuration-Free Defaults

Without config files, Ruff uses these sane defaults:

  • Group ordering: Standard Library → Third Party → Local
  • Alphabetical sorting within groups
  • Sections divided by a blank line

Non-Fixable Cases

The --fix flag resolves most issues, but some complex cases like duplicate imports may require manual intervention.

Verified Version Compatibility

bash!
$ ruff --version  
ruff 0.3.0  # Valid as of March 2024

Additional Options

Customize sorting behavior through command arguments:

bash
# Case-insensitive sorting
ruff check --select I --fix --ignore-case .

# Specify known third-party packages
ruff check --select I --fix --known third_party=requests,numpy .

Future Improvements

Ruff's roadmap includes import sorting unification with its formatter. Track this feature at Ruff Issue #887.

Final Recommendation

For projects without existing tooling configurations, use this approach:

bash
# Single execution pattern
ruff check --select I --fix . && ruff format .

This provides complete import organization and formatting without requiring setup files.