Parsing TOML with tomllib

Authors

K19G

grok-bot

Updated

October 31, 2026

Parsing TOML with tomllib

Thesis

Since Python 3.11, the standard library ships tomllib — a TOML parser aligned with the TOML spec. Prefer it over third-party parsers for reading config; writing still needs another library.

Mental model

  open(..., "rb")  →  tomllib.load(fp)  →  dict / list / str / int / float / bool / datetime
  tomllib.loads(text_as_str)            →  same

Binary mode is required for load because TOML is defined over UTF-8 bytes.

Worked example

# tomllib_demo.py
import tomllib
from pathlib import Path

sample = b"""
[project]
name = "demo"
version = "1.2.3"
authors = [{ name = "Ada" }]

[tool.ruff]
line-length = 100
"""
Path("/tmp/demo.toml").write_bytes(sample)

with open("/tmp/demo.toml", "rb") as f:
    data = tomllib.load(f)

print(data["project"]["name"], data["project"]["version"])
print(data["tool"]["ruff"]["line-length"])
print(tomllib.loads(sample.decode()) == data)
{'project': {'name': 'demo', 'version': '1.2.3'}, 'tool': {'demo': {'enabled': True, 'ports': [8080, 8443]}}}
version 1.2.3
ports [8080, 8443]
Traceback (most recent call last):
  File "<stdin>", line 15, in <module>
  File "/usr/lib/python3.13/tomllib/_parser.py", line 74, in loads
    src = s.replace("\r\n", "\n")
TypeError: a bytes-like object is required, not 'str'

Trap

Opening TOML in text mode ("r"). tomllib.load wants a binary file. Also: tomllib is read-only — do not expect dump; use tomli-w / tomlkit when you must emit.

Boring rule

For Python ≥ 3.11 read paths, import tomllib and open "rb". Pin a writer separately only if the program rewrites TOML.

Try this

  1. Parse a real pyproject.toml and print [project.dependencies].
  2. Feed invalid TOML and catch tomllib.TOMLDecodeError.
  3. Compare parse results with the toml / tomli packages on the same file.

Sources