# Replace Black and isort With Ruff in a Python Project

Yes. An agent replaces Black and isort with Ruff, separates the formatting churn from the tool change, repairs the CI check, and opens a reviewable pull request.

[Run this on Rush](https://cloud.getrush.ai/run/migrate-black-to-ruff/black/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent measures the starting point with the versions the repository pins, because a format migration is only reviewable when the baseline is known. In a project like ExpDev07/coronavirus-tracker-api the `Pipfile` pins `black` to `19.10b0` and the lockfile holds isort 5.7.0. `pyproject.toml` configures both: a line length of 100, Black targets `py36` to `py38`, and an isort block with `multi_line_output = 3` and two `known_third_party` names. Run as pinned, `black --check .` reports that 4 files would be reformatted and 37 left unchanged. The code has drifted from its own formatter, which should have been impossible with a formatting check in CI.

So the agent reads how the check is wired, and finds out why it never failed. `.travis.yml` runs `make check-fmt`, the `Makefile` calls `invoke check --fmt --sort`, and the `check` task in `tasks.py` joins `black --check .` and `isort --check .` with a single `&`, under a comment that reads `FIXME: run each command and check return code`. A single `&` puts Black in the background, and the shell returns isort's status alone. The agent proves it by adding a badly formatted file: `black --check` exits 1, while `invoke check --fmt --sort` and `make check-fmt` both exit 0. It also installs `black==19.10b0` into a fresh environment without the lockfile, as the CI file's `--skip-lock` does, and gets `ImportError: cannot import name '_unicodefun' from 'click'`.

Next it sizes the change and attributes it. With `line-length = 100`, `ruff format --check` wants to reformat 28 of 45 files. That number says little until it is compared with something, so the agent runs a current Black with the repository's own settings: 28 files as well. The churn comes from five years of style changes, not from switching tools. The diff shows what they are: a blank line after each module docstring, and collections that Black 19.10b0 packed onto one line with a trailing comma now written one element per line. For imports, Ruff's `I` rule with the same `known-third-party` names disagrees with isort in one place, `app/services/location/jhu.py`, where it merges two `from ...utils import` lines that isort kept apart.

It then makes the change in commits a reviewer can separate. The first replaces the tooling: `[tool.ruff]` with the line length and `target-version = "py38"`, the `I` rule and its isort settings, `ruff` in place of `black` and `isort` in the dev dependencies, and a `check` task that runs `ruff format --check` and `ruff check` as two commands and fails when either does. The second is the output of `ruff format .` and `ruff check --fix .` with no manual edits, and its hash goes into `.git-blame-ignore-revs`. The test suite runs before and after with the same result, and the planted bad file now fails `make check-fmt`.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Replace Black and isort with Ruff in this repository. Start by measuring: install the exact black and isort versions the lock or requirements files pin, run black --check and isort --check, and record how many files each would change. Read how formatting is checked in CI, following every indirection (CI file, Makefile, task runner, pre-commit) down to the shell command that runs, and test whether the check can fail: add a deliberately misformatted file, run the same entry point CI runs, and report the exit code. If the check cannot fail, explain exactly why. Also install the pinned Black into a fresh environment the way CI installs dependencies and report whether it starts. Then translate the [tool.black] and [tool.isort] settings to [tool.ruff], run ruff format --check and ruff check with the import rule, and report file counts. To attribute the churn, run the newest Black that supports this project's Python with the existing settings and compare its count with Ruff's; show three representative hunks. List every place where Ruff's import sorting differs from isort's. Make two commits: one with configuration, dependency, task and CI changes, one with only the formatter's output, and add the second commit's hash to .git-blame-ignore-revs. Fix the check so it fails on unformatted code and prove it with the misformatted file, then delete that file. Run the tests before and after. Do not enable lint rules beyond import sorting. Open a pull request with the output of every command.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request in two commits. The first changes `pyproject.toml`, the dependency files, `tasks.py`, the `Makefile` if its targets change, the CI file and the README's formatting section. The second touches only Python sources and is mechanical. The description states the size of that second commit and where it comes from, with the three counts side by side: the pinned Black, a current Black, and Ruff. A reviewer who sees that the last two match can skip reading the formatting diff line by line.

The description also documents the broken check, since that is a finding about the repository and not about Ruff. It quotes the task's command string, shows the exit codes with a misformatted file before and after the fix, and notes that formatting was never enforced on any pull request merged while the old task was in place. The single import-sorting difference is shown as a diff hunk.

Before merging, the reviewer confirms that the test totals are identical before and after, that `[tool.black]` and `[tool.isort]` are gone so no editor plugin keeps applying the old style, and that `.git-blame-ignore-revs` holds the hash of the commit as it will exist on the default branch. A squash merge changes that hash, so the description says which merge method the file assumes.

## Run it on every Python repository still on Black

This runs once for each repository, started by whoever owns the decision. Send the body to `POST /o/{org}/sessions` from a terminal or an MCP client and include a `request_id`, a UUID made for the job. A formatting change conflicts with every open branch, so choose the moment: add a line to `input` that tells the agent to stop after the measurements, then send a follow-up to `POST /o/{org}/sessions/{id}/messages` asking for the commits when the team is ready. The sandbox keeps the environments it built in between.

To keep the result true afterwards, add an automation to the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize`, a short prompt that runs the format check and comments with the files that fail, and the read-only setting on, so its runs can read and comment but not push. The pull request event is placed after the prompt as data. Pull requests from forks do not fire the trigger.

## Why run it on Rush?

The objection to every formatter migration is the size of the diff, and the answer is evidence about where the diff comes from. That evidence means installing three formatters, one of them old enough to need a matching Python and a matching `click`, and running each over the same tree. In its own sandbox the agent builds those environments from nothing and keeps each command's output in the transcript at `GET /o/{org}/sessions/{id}/messages`. The counts in the pull request are the counts in that record.

The run also tests the check instead of reading it. A task that joins two commands with `&` looks plausible in review and has passed CI for years. Only planting a bad file and reading the exit code shows that it cannot fail. A run does that as a matter of course, on a machine where a stray global install of Black cannot mask the import error a fresh CI environment would hit.

## Frequently asked questions

### Will Ruff format my code exactly like Black does?

Close to a current Black, and not like a Black from 2019. Ruff's formatter is designed as a drop-in replacement for the current Black style, so a repository formatted with a recent Black changes very little. A repository pinned to an old release sees the accumulated style changes all at once, which is what the three-way count in the pull request makes visible.

### Do I need a separate tool for import sorting?

No. Ruff's `I` rule sorts imports and `ruff check --fix` applies it. The formatter does not sort imports, so both commands are needed, in that order of responsibility: the linter orders the import block and the formatter lays it out. Settings such as `known-third-party` move to `[tool.ruff.lint.isort]`.

### How do I keep git blame useful after a formatting commit?

List the formatting commit's hash in `.git-blame-ignore-revs` at the repository root. GitHub's blame view reads that file, and `git config blame.ignoreRevsFile .git-blame-ignore-revs` makes the command line do the same. The commit must contain only formatter output for this to be honest, which is why the request separates it from the configuration commit.

### Can I keep isort and only replace Black?

You can, but check that the two agree first. On the fixture this page was written against, Ruff's import rule and isort 5.7.0 disagree on one file, so enforcing both would fail in one direction or the other. Running one import sorter is simpler, and the agent removes isort's configuration so no editor keeps applying it.

## More Black jobs

- [Fix "ImportError: cannot import name '_unicodefun' from 'click'" in Black](https://getrush.ai/run/fix-cannot-import-name-unicodefun-from-click/black/)

## More jobs like this: Hand off a long task

- [Migrate a Python Project from CircleCI to GitHub Actions](https://getrush.ai/run/migrate-circleci-to-github-actions/circleci/)
- [Migrate a Click CLI to Typer](https://getrush.ai/run/migrate-click-to-typer/click/)
- [Migrate a Node.js App from CommonJS to ESM](https://getrush.ai/run/migrate-commonjs-to-esm/nodejs/)
- [Migrate a Create React App Project to Vite](https://getrush.ai/run/migrate-create-react-app-to-vite/create-react-app/)
- [Replace dotenv With Node's --env-file Flag in an Express App](https://getrush.ai/run/migrate-dotenv-to-env-file/dotenv/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
