# How to sort Python imports with Ruff

{{< callout type="warning" >}}
This guide assumes you have uv installed. If you haven't installed uv yet, follow the [installation instructions](https://docs.astral.sh/uv/getting-started/installation/) before proceeding.
{{< /callout >}}

This guide shows how to automatically organize and sort Python imports using Ruff. Import sorting is one of Ruff's lint rules; for everything else it checks and formats, see [Ruff: a complete guide](https://pydevtools.com/handbook/explanation/ruff-complete-guide.md).

## Sorting a Single File

To sort imports in a Python file called `example.py`:

```console
$ 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:

```console
$ uvx ruff check --select I --fix .
```

## Using Ruff in a Project

For ongoing import sorting in a project:

1. Add [Ruff](https://pydevtools.com/handbook/reference/ruff.md) as a development dependency:
```console
$ uv add --dev ruff
```

2. Configure Ruff in [pyproject.toml](https://pydevtools.com/handbook/reference/pyproject.toml.md):
```toml
[tool.ruff.lint]
extend-select = ["I"]
```

3. Run import sorting with:
```console
$ uv run ruff check --fix .
```

## Learn More

- [Ruff](https://pydevtools.com/handbook/reference/ruff.md) reference
- [How to configure recommended Ruff defaults](https://pydevtools.com/handbook/how-to/how-to-configure-recommended-ruff-defaults.md)
- [How to enable Ruff security rules](https://pydevtools.com/handbook/how-to/how-to-enable-ruff-security-rules.md)
- [Ruff: a complete guide](https://pydevtools.com/handbook/explanation/ruff-complete-guide.md)
