# Replace the toml Package With Python's Built-In tomllib

Yes. An agent swaps the unmaintained toml package for tomllib, keeps Python 3.10 working through tomli, and proves your config files still parse.

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

## What the agent does

The `toml` package on PyPI has had no release since 0.10.2 in November 2020, and Python 3.11 added a TOML reader to the standard library. The agent begins by listing every place the old package is named, which is usually more places than it is imported. In a project like bofh69/nfc2klipper the import is one line, `import toml` in `lib/config.py`, and the only call is `toml.load(fp)` in `get_config`. The name appears in six other places: `toml==0.10.2` and `types-toml` in `requirements.txt`, the same pin in the inline script metadata at the top of `nfc2klipper_backend.py` and `nfc2klipper_api.py`, `types-toml` in the `Makefile` rule that installs mypy and in `.github/workflows/mypy.yml`, and a `[mypy-toml.*]` section in `mypy.ini`.

Two details decide the shape of the change. The first is the file mode. `get_config` opens the file with `open(cfg_filename, "r", encoding="utf-8")`, and `tomllib.load` refuses a text file with `TypeError: File must be opened in binary mode`. The agent changes the mode to `"rb"` and drops the encoding argument, since TOML is UTF-8 by definition. The second is the Python floor. The README and the script metadata say Python 3.9 or newer, CI checks 3.10 to 3.14, and `tomllib` exists only from 3.11. So the agent adds `tomli; python_version < "3.11"`, the package `tomllib` was built from, and imports one or the other.

How that import is written matters here because the project type-checks. The agent tries both common forms under mypy. A `try: import tomllib` with `except ModuleNotFoundError: import tomli as tomllib` fails for a 3.10 target with `Cannot find implementation or library stub for module named "tomllib"`. The form mypy follows is `if sys.version_info >= (3, 11): import tomllib` with `else: import tomli as tomllib`, and that is the one it commits. It removes `types-toml` from all three places and the `[mypy-toml.*]` section, because both readers ship their own types.

Then it checks that real configuration still loads the same. It parses the repository's default `nfc2klipper.cfg` with the old and the new reader and compares the two dicts, including the multi-line `setting_gcode` and `clearing_gcode` strings and the nested `[opentag3d.filament_field_mapping]` table. It also feeds both readers a short list of edge cases and reports where they disagree: `tomllib` accepts an array that mixes types, which `toml` 0.10.2 rejects as `Not a homogeneous array`, and it refuses a raw control character inside a string and a `[a.c]` header that extends an inline table `a`, both of which the old package let through. A config file on a user's machine that relied on either leniency would stop loading, so the pull request names them.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Replace the third-party toml package with the standard library's tomllib in this Python project. Find every place toml is named: imports, requirements files, inline script metadata, pyproject or setup files, the Makefile, CI workflows and mypy or pylint configuration, including type stub packages such as types-toml. List each call: load, loads, dump, dumps and any except clause that names TomlDecodeError. If the code writes TOML with dump or dumps, stop and report it, because tomllib only reads. Otherwise make the change: open files in binary mode for tomllib.load, and map TomlDecodeError to tomllib.TOMLDecodeError. Read the minimum Python version the project states in its README, metadata and CI matrix; if any supported version is older than 3.11, add tomli with a python_version marker and import it under the name tomllib, using the import form the project's type checker accepts, and show the checker's output for the form you rejected. Before and after, parse every TOML or TOML-format config file in the repository with both readers and print whether the results are equal. Run both readers on a list of edge cases (mixed-type arrays, duplicate keys, a byte order mark, control characters in strings, a table header that extends an inline table) and report the cases where one accepts and the other refuses. Run the project's own lint and type-check targets on the oldest and newest Python version in its CI matrix. Give any new file the license header the repository's other files carry. Open a pull request with the comparison output.",
  "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 that edits `lib/config.py`, `requirements.txt`, the metadata block of the two scripts, the `Makefile`, `mypy.yml` and `mypy.ini`. The description shows the equality check on `nfc2klipper.cfg`, the table of edge cases with each reader's answer, and the output of `make lint` and `make typecheck` on Python 3.10 and on the newest version in the matrix. It states that the code never writes TOML: `install_config` copies the default file with `shutil.copyfile`, so nothing needed a writer such as `tomli-w`.

The reviewer looks at the marker on the `tomli` line, at the guard in the import, and at the list of inputs the new reader refuses. They also read one finding the agent reports without acting on it: `mypy.ini` sets `python_version = 3.9`, and a current mypy answers that 3.9 is not supported and must be 3.10 or higher. Whether to raise that setting, and with it the stated floor, is a decision for the maintainer. This repository also runs `reuse lint` in CI, so a test file added without an SPDX header would fail a check that has nothing to do with TOML; the agent copies the header format the other sources use.

## Run it on every repository that still pins toml

The same three-line change repeats across every tool that reads a config file, and each one has its own Python floor and its own lint setup. From a script, search your organisation's requirement files for a `toml==` pin and send this body once per repository to `POST /o/{org}/sessions`, with that repository in `resources`. Include a `request_id` that is a UUID v5 of the repository name, so a second pass of the script returns the earlier runs and starts nothing new.

Each run answers `202` at once. Poll `GET /o/{org}/sessions/{id}` for the pull request, or set a `webhook_url` on the key and receive `run.completed` for every run that key started.

## Why run it on Rush?

The change is only safe if it holds on every Python version the project claims, and a laptop has one of them on the path. The run creates a 3.10 and a newest-version environment in its sandbox, runs the project's own `make` targets in each, and keeps both outputs. The import form that mypy rejected is in the transcript with its error, which is the reason the committed form looks the way it does.

Parser swaps fail on inputs nobody thought to try. The agent tries them deliberately, with both readers installed side by side, and the differences become a short table in the pull request. That table is the evidence a maintainer needs before shipping a new reader to machines whose config files they have never seen.

## Frequently asked questions

### Why does tomllib.load raise "File must be opened in binary mode"?

`tomllib.load` takes a binary file object so that it can decode UTF-8 itself and handle newlines the way the TOML specification requires. Open the file with `"rb"` and remove any `encoding` argument. `tomllib.loads` takes a `str` if you already have the text.

### What do I use on Python 3.10 or older?

The `tomli` package, which has the same `load` and `loads` functions and became `tomllib` in 3.11. Add it with the marker `python_version < "3.11"` and import it as `tomllib` behind a `sys.version_info` check. The agent only adds it when the project still supports a version below 3.11.

### Can tomllib write TOML files?

No. It reads only. A project that calls `toml.dump` or `toml.dumps` needs a writer such as `tomli-w`, and its output formatting is not identical to the old package's. The prompt tells the agent to stop and report in that case, so the swap is never done halfway.

### Will my existing config files still load?

Valid TOML loads the same; the agent compares the parsed result of every config file in the repository under both readers. `tomllib` follows TOML 1.0 strictly, so a file that only loaded because the old package was lenient can now raise `TOMLDecodeError`. The pull request lists the cases it found.

## More jobs like this: Upgrade dependencies weekly

- [Migrate golang.org/x/exp/slices and maps to the Go Standard Library](https://getrush.ai/run/migrate-x-exp-slices-to-slices/golang-x-exp/)
- [Migrate golang.org/x/net/context to the Standard Library context Package in Go](https://getrush.ai/run/migrate-x-net-context-to-context/x-net-context/)
- [Pin Docker Base Images by Digest](https://getrush.ai/run/pin-image-versions/docker/)
- [Pin and Upgrade Container Images in Docker Compose](https://getrush.ai/run/pin-image-versions/docker-compose/)
- [Pin and Upgrade Container Images in Kustomize Manifests](https://getrush.ai/run/pin-image-versions/kustomize/)
- [Pin the Python Dependencies of a Streamlit App](https://getrush.ai/run/pin-python-dependencies/streamlit/)

## 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/)
