TOML in Rust and Python
How to parse and generate TOML in Rust (serde_toml) and Python (tomllib/tomli) — with examples.
Published:
Tags: TOML Rust Python, serde TOML Rust, Python tomllib
TOML in Rust and Python TOML is the native configuration format for Rust (Cargo.toml) and Python (pyproject.toml). Both ecosystems have first-class TOML support — Rust through serde + the toml crate, Python through the stdlib tomllib (3.11+) or tomli/tomli-w. The TOML 1.0 specification defines the format authoritatively. The Rust Cargo documentation and Python PEP 517/518 define pyproject.toml usage. --- TOML Quick Reference See the TOML specification for the full grammar. Python: Reading TOML with tomllib (3.11+) Python: Reading TOML on Python 3.10 and Earlier Python: Writing TOML with tomli-w Output: Python: pyproject.toml Parsing Rust: Reading TOML with serde Rust: Writing TOML with serde TOML Type Compatibility: Python vs Rust | TOML Type | Python (tomllib) | Rust (serde+toml) |…
Frequently Asked Questions
How do I parse TOML in Python?
Python 3.11+ includes `tomllib` in the standard library. Open the file in binary mode and call `tomllib.load(f)`. For Python 3.10 and earlier, install `tomli` (read-only) with `pip install tomli`. For writing TOML, use `tomli-w`.
What is the tomllib module in Python 3.11?
tomllib is a TOML 1.0-compliant parser added to Python's standard library in Python 3.11 (PEP 680). It provides `tomllib.load(file)` and `tomllib.loads(string)`. It is read-only — for writing TOML, use the third-party `tomli-w` package.
How do I use serde for TOML in Rust?
Add `serde = { version = '1.0', features = ['derive'] }` and `toml = '0.8'` to Cargo.toml. Derive `Deserialize` on your config struct, then call `toml::from_str(&content)?`. For writing, derive `Serialize` and call `toml::to_string_pretty(&config)?`.
How do I write TOML in Python?
Install `tomli-w` with `pip install tomli-w`. Build a Python dict with your data (strings, ints, floats, bools, lists, dicts, datetime objects) and call `tomli_w.dumps(data)` for a string or `tomli_w.dump(data, file)` for a file. None values are not supported.
What is the Cargo.toml format?
Cargo.toml is Rust's package manifest file, written in TOML. It defines package metadata (name, version, edition), dependencies (with version requirements and features), dev-dependencies, build scripts, and workspace configuration. It is parsed by Cargo at build time.
All articles · theproductguy.in