Lesson · Standard Data Formats
TOML with tomllib
55 min readTOML with tomllib
`tomllib` parses TOML into Python data structures using the standard library. TOML is common for project configuration, especially `pyproject.toml`, but `tomllib` intentionally does not write TOML.
Learning goals
- Load TOML from a string with
tomllib.loadsand from a binary file withtomllib.load, and say which input type each accepts. - Read nested tables as nested Python dicts and index into a
pyproject.toml[project]section. - Map TOML types (string, integer, float, boolean, array, table, date-time) to their Python counterparts.
- Explain why
tomllibis read-only and what that means for editing configuration. - Predict what
tomllib.TOMLDecodeErrorreports for a malformed document.
Mental model
Parsing and trusting are separate steps: tomllib turns text into ordinary Python containers and will not tell you whether the values make sense, only whether the syntax was valid. Nested [table] headers arrive as nested dicts, so access follows the same path you see in the document.
Mental model
read it top to bottom
TOML document (str or binary file) ↓ tomllib.loads / tomllib.load plain dicts, lists, and scalars ↓ your validation configuration your code can trust
Core idea
TOML's structure maps almost one-to-one onto Python's core data types, which is why tomllib needs no schema: a document parses into nested dicts, lists, and scalars. The library stops at syntax, so the design questions sit after the parse: which sections are required, how values are validated, and how the program behaves when a file is missing or malformed. tomllib reads; any writing needs a separate library.
TOML as a configuration format
TOML is a text configuration format built around obvious mappings: key = value pairs, [table] headers for nesting, arrays, and native date-time values, so files stay readable without indentation rules. It is the format of pyproject.toml, and its type set is specified precisely enough that the same document parses to the same structure in any language.
tomllib.load
tomllib.load(file) reads a TOML document from a binary file object (open the file with "rb" or use an io.BytesIO) and returns its contents as a dict. It reads to end of file, requires the bytes to be valid UTF-8, and raises tomllib.TOMLDecodeError for invalid syntax.
tomllib.loads
tomllib.loads(document) parses TOML that is already a str and returns the same dict structure as load; it does not accept bytes, so decode first if the source was binary. Both functions reject duplicate keys and malformed values with tomllib.TOMLDecodeError.
Reading pyproject.toml
pyproject.toml holds a project's build metadata, and its [project] table carries fields such as name, version, and dependencies. Reading it at runtime is the same as reading any TOML file: open with "rb", call tomllib.load, and index config["project"]["name"]; packaging tools apply their own extra validation on top.
TOML types
TOML's types map directly: strings, integers, floats, and booleans become str, int, float, and bool; arrays become lists; tables become dicts; and offset or local date-times become datetime.datetime or datetime.date objects. That precision is what lets a parsed value be used without further conversion.
Read-only role of the standard-library tomllib module
The standard-library tomllib only parses; it has no writer. That is deliberate: editing a user's configuration file in place loses comments and formatting, so writing is delegated to third-party libraries such as tomli-w. Code that must round-trip a file should treat the document as read-only input and keep edits elsewhere.
Configuration parsing vs validation
Parsing answers one question: is this document valid TOML? Validation answers another: does this project's configuration make sense, with the required keys and acceptable values? tomllib guarantees the first and nothing about the second, so a program should check required sections and value ranges itself and report its own errors.
Walkthrough
documentis abytesliteral holding the TOML text, anddocument.decode()converts it to thestrthattomllib.loadsrequires.- The
[project]and[tool.demo]headers produce nested dicts:config["project"]["name"]is"demo", andconfig["tool"]["demo"]["strict"]is the PythonTrue, because TOML booleans map tobooldirectly. - The blank lines inside the document are insignificant to the parser; structure comes only from headers and key-value pairs.
- Predict before running: the two printed lines, then what error
tomllib.loads(document)raises if the.decode()call is removed.
Experiments to try
- Add
created = 2026-01-15T09:30:00Zto the document, parse it, and printtype(config["created"]); check the value againstdatetime.datetime. - Store the document in a
pyproject.tomlfile and load it withopen(path, "rb")andtomllib.load; compare the result withloadson the decoded text. - Introduce a duplicate key and read the
tomllib.TOMLDecodeErrormessage; note whether it names a line number. - Add
dependencies = ["requests>=2", "rich"]under[project]and index the list; then index a string as if it were a dict and read theTypeError.
Common mistakes
- Passing bytes to
tomllib.loads: the string version acceptsstronly, so decode first or switch totomllib.loadwith a binary file. - Treating
tomllibas a full round-trip reader and writer: it cannot write, and naive rewrites of a config file lose comments and formatting, so keep edits manual or use a purpose-built writer. - Assuming the file sits in the working directory:
Path("pyproject.toml")resolves against wherever the program was started, so locate it relative to__file__or an explicit root. - Skipping validation because the document parsed: a syntactically valid file can still miss the table your code expects, and the failure then surfaces as a
KeyErrorfar from the load site.
Practice: Easy
- Parse the worked example's document and print
type()and value for thenameandstrictentries; annotate which TOML type each came from. - Add an array field to the document, parse it, and assert its Python type is
list. - Feed
tomllib.loadsa string with a missing closing bracket and print theTOMLDecodeErrormessage.
Practice: Medium
- Write a small
pyproject.toml, load it withtomllib.load, and buildproject_name()that returnsNonewhen the[project]table is absent instead of raisingKeyError. - Round-trip a TOML document by parsing it, modifying the resulting dict, and printing it with
pprint; explain which formatting was lost compared with the original text. - Convert the parsed document to JSON and compare the two structures; list two TOML features (comments, native dates) that do not survive an unconsidered conversion.
Practice: Hard
- Design a config loader with defaults: read
pyproject.tomlwhen present, otherwise use built-in values, validate required keys, and return a typed config. Write one test for each branch. - Build a reporter that walks a parsed TOML structure and prints every table path (
project,tool.demo) with its key count; use recursion and decide how to handle arrays of tables. - Investigate write-back: take a hand-written TOML file with comments, mutate one value (with a third-party writer if available or manual text editing), and compare the result's formatting with the original; state when write-back is acceptable.
Lesson checklist
- I can choose
loadorloadsbased on whether my input is a binary file or a string. - I can map each TOML type in a document to its Python type after parsing.
- I can explain why
tomllibcannot write and what that implies for round trips. - I can validate required tables myself and name the error a missing one should produce.
Remember
`tomllib` converts a TOML document into ordinary `dict`, `list`, and scalar values with a precise type mapping, and stops there: parsing says the syntax is valid, not that the configuration is complete or sensible. Load with the right variant for the input (`load` for binary files, `loads` for strings), expect `TOMLDecodeError` for malformed text, and validate the structure yourself before use.
Interview angles
What is the main purpose of **TOML as a configuration format**?+
TOML is a text configuration format with key = value pairs, [table] headers, arrays, and native date-time values, which keeps files readable without indentation rules. It is the format of pyproject.toml, and its types parse to the same structure in any language.
What should you pay attention to when using **tomllib.load**?+
tomllib.load(file) reads a binary file object, expects valid UTF-8, and returns the document as a dict; invalid syntax raises tomllib.TOMLDecodeError. Use it with open(path, "rb") when the source is a file.
How does **tomllib.loads** fit into this lesson?+
tomllib.loads parses TOML that is already a str and returns the same dict structure as load; it does not accept bytes, which is why the worked example decodes first. Both variants reject duplicate keys and malformed values.
Why does `tomllib.loads(document)` fail when `document` is a bytes literal, and what are the two fixes?+
The function parses str only; either decode the bytes (document.decode()) or keep the data in a binary file and use tomllib.load instead.