Python tomllib — Parse TOML with Loads and Load
Project settings, tool options, and program configuration now live in TOML files, and Python reads them with one small module. The tomllib module parses a TOML string or file into plain dictionaries, lists, and values, with no package to install. This guide takes the two entry points in turn, then the value types, nested tables, dotted keys, multiline strings, integer forms, and the errors that invalid files raise.
Written November 15, 2026 · Tested with Python 3.12.3 · 10 min read
- The main program: loads and load
- Value types: what each TOML type becomes
- Nested tables and arrays of tables
- Dotted keys: structure without headers
Written November 15, 2026
Tested with Python 3.12.3
What this guide is
The tomllib module parses TOML, the configuration format behind files such as pyproject.toml. It has two entry points and nothing else to learn at the top level: loads parses a string the program already holds, and load parses a file object opened in binary mode. Both return the same thing, a dictionary that holds the whole document, with tables as nested dictionaries and arrays as lists. The module only reads. It has no writer, so a program that needs to produce TOML writes the text itself or uses a separate package. The module arrived in Python 3.11, so any current Python has it in the standard library.
The main program: loads and load
loads takes a string and returns the document as a dictionary. load takes a file object and returns the same dictionary for the same text. The file object must be binary: open the file with mode "rb", because the parser reads bytes and works out the encoding itself. The program below parses the same small document both ways, the second time through an in-memory bytes stream that stands in for the opened file:
import tomllib, io
data = tomllib.loads('title = "Demo"\nversion = 2\n')
print(data)
print(type(data).__name__)
with io.BytesIO(b'title = "Demo"\nversion = 2\n') as f:
print(tomllib.load(f))
The exact output:
{'title': 'Demo', 'version': 2}
dict
{'title': 'Demo', 'version': 2}
A real file follows the same shape: with open("pyproject.toml", "rb") as f: data = tomllib.load(f). Everything after the parse is plain dictionary work: keys are the TOML keys as strings, and a missing key raises the usual KeyError, so configuration code reads values with the same .get and default patterns it uses for any other dictionary. The parse is all or nothing: a document with one bad line raises an error and returns no partial result.
Value types: what each TOML type becomes
Each TOML value lands as a Python value of a matching kind. A string stays a string, an integer becomes an int, a number with a fraction or an exponent becomes a float, and true and false become booleans. The date and time forms become objects from the datetime module: a value with a date, a time, and an offset becomes a datetime with its time zone set, a date alone becomes a date, and a time alone becomes a time. An array becomes a list, and a table becomes a dictionary:
import tomllib
text = """
name = "toml-demo"
count = 42
ratio = 1.5
enabled = true
stamp = 2026-11-15T09:30:00Z
day = 2026-11-15
clock = 09:30:00
tags = ["a", "b"]
[owner]
name = "Ada"
"""
data = tomllib.loads(text)
print(data)
print({k: type(v).__name__ for k, v in data.items()})
print(data["stamp"], data["day"], data["clock"])
The exact output:
{'name': 'toml-demo', 'count': 42, 'ratio': 1.5, 'enabled': True, 'stamp': datetime.datetime(2026, 11, 15, 9, 30, tzinfo=datetime.timezone.utc), 'day': datetime.date(2026, 11, 15), 'clock': datetime.time(9, 30), 'tags': ['a', 'b'], 'owner': {'name': 'Ada'}}
{'name': 'str', 'count': 'int', 'ratio': 'float', 'enabled': 'bool', 'stamp': 'datetime', 'day': 'date', 'clock': 'time', 'tags': 'list', 'owner': 'dict'}
2026-11-15 09:30:00+00:00 2026-11-15 09:30:00
Two details in that output are worth keeping. The Z at the end of the stamp is an offset, so the value is a datetime whose time zone is set to UTC, and printing it shows the +00:00 suffix. A date-time written with no offset at all becomes a datetime with no time zone, the local form. And the [owner] header starts a table: every key after the header belongs to that table until the next header, which is why name appears twice in the document and once inside the owner dictionary in the result.
Nested tables and arrays of tables
A table header with dots in it builds nesting: [server.tls] is a table named tls inside the table named server, and the parent table needs no header of its own first. A header written with double brackets, [[products]], starts an array of tables instead: each double-bracket header appends one new dictionary to the list under that name, and the keys that follow belong to the new entry:
import tomllib
text = """
[server]
host = "example.com"
port = 8080
[server.tls]
enabled = true
[[products]]
name = "Hammer"
price = 12
[[products]]
name = "Nails"
price = 3
"""
data = tomllib.loads(text)
print(data["server"])
print(data["server"]["tls"])
print(data["products"])
print(data["products"][0]["name"], data["products"][1]["price"])
print(len(data["products"]))
The exact output:
{'host': 'example.com', 'port': 8080, 'tls': {'enabled': True}}
{'enabled': True}
[{'name': 'Hammer', 'price': 12}, {'name': 'Nails', 'price': 3}]
Hammer 3
2
Reading the result is ordinary indexing: dictionaries for tables, lists for arrays of tables. The order of entries in an array of tables is the order of the headers in the file, so list position is a stable way to refer to an entry. A single-bracket header used twice for the same table is an error, while the double-bracket form is the one place where repeating a header is the whole point.
Dotted keys: structure without headers
A key can carry dots, and each dot steps one level deeper. a.b.c = 1 builds the same nested dictionaries as a [a.b] header with c = 1 under it, and several dotted keys that share a prefix build one shared structure. Dotted keys suit short documents and small groups of related settings, where a header per group would spread a few values across many lines:
import tomllib
text = """
a.b.c = 1
a.b.d = 2
fruit.apple.color = "red"
fruit.apple.weight = 150
"""
data = tomllib.loads(text)
print(data)
print(data["a"]["b"])
print(data["fruit"]["apple"]["color"])
The exact output:
{'a': {'b': {'c': 1, 'd': 2}}, 'fruit': {'apple': {'color': 'red', 'weight': 150}}}
{'c': 1, 'd': 2}
red
The two forms mix in one document, but a name can only be defined once: a key first built by a dotted key cannot be opened again as a table header later in the file, and the reverse holds too. When a parse fails with an overwrite error, a dotted key and a header that claim the same name are the first place to look.
Multiline strings: basic and literal
TOML has two string forms that span lines. A multiline basic string opens and closes with three double quotes; escape sequences still work in it, and the newline right after the opening quotes is trimmed, so the value starts with the first line of text. A multiline literal string opens and closes with three single quotes; nothing inside it is an escape, so a path with backslashes is written as it stands:
import tomllib
basic_doc = '''
basic = """first line
second line"""
'''
literal_doc = """
literal = '''C:\\path\\to\\file'''
"""
print(repr(tomllib.loads(basic_doc)["basic"]))
print(repr(tomllib.loads(literal_doc)["literal"]))
print(tomllib.loads(basic_doc)["basic"])
The exact output:
'first line\nsecond line'
'C:\\path\\to\\file'
first line
second line
The literal form is the safe home for Windows paths and for any text where a backslash means a backslash: in a basic string the same text would need each backslash doubled, and one missed doubling changes the value or breaks the parse. The single-line forms follow the same split: single quotes make a literal string, double quotes make a basic string with escapes. Long help text and sample output in a configuration file are the usual multiline cases.
Integer forms: hex, octal, binary, and underscores
An integer can be written in four bases. Plain decimal is the default, a 0x prefix makes the value hexadecimal, 0o makes it octal, and 0b makes it binary. Underscores can sit between digits as visual grouping in any of the forms, and the parser drops them. Every form lands as the same Python int, so the file can use the base that suits the value, such as a permission mask in octal or a flag set in binary:
import tomllib
text = """
plain = 42
negative = -17
hex = 0xFF
octal = 0o17
binary = 0b1010
grouped = 1_000_000
"""
data = tomllib.loads(text)
print(data)
print(data["hex"], data["octal"], data["binary"], data["grouped"])
The exact output:
{'plain': 42, 'negative': -17, 'hex': 255, 'octal': 15, 'binary': 10, 'grouped': 1000000}
255 15 10 1000000
An underscore has to sit between two digits: a leading, trailing, or doubled underscore is invalid TOML and raises the decode error covered next. Floats take the same grouping, and a float can also carry an exponent, as in 1.5e3.
The traps: TOMLDecodeError and the binary-mode rule
tomllib.TOMLDecodeError, a subclass of ValueError. The message names the problem and, where the parser can point at it, the line and column. Three failures cover most of what a hand-edited file produces: a key with no value, a key defined twice, and an array that never closes. A fourth trap sits one step earlier: load on a file opened in text mode raises a TypeError before any parsing happens, because the parser needs bytes:import tomllib, io
bad = ["title = ", "name = 1\nname = 2\n", "value = [1, 2\n"]
for doc in bad:
try:
tomllib.loads(doc)
except tomllib.TOMLDecodeError as e:
print(type(e).__name__ + ":", e)
try:
tomllib.load(io.StringIO("a = 1"))
except TypeError as e:
print("TypeError:", e)
The exact output:
TOMLDecodeError: Invalid value (at end of document)
TOMLDecodeError: Cannot overwrite a value (at line 2, column 9)
TOMLDecodeError: Unclosed array (at end of document)
TypeError: File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`
The handling pattern follows from the shapes. Catch TOMLDecodeError around the parse of any file the program does not control, and report the message as it stands: it is written for the person who edits the file, and it carries the position when one is known. Open files with "rb" as a habit, not as a fix after the error. And treat a failed parse as no configuration at all: the parser returns nothing partial, so falling back to defaults is a decision the program makes in the exception handler, not a state it can drift into.
Which choice for which job
| Job | Choice | Why |
|---|---|---|
| Parse a string the program holds | loads |
Takes a str directly |
| Parse a file on disk | load with "rb" |
Reads a binary file object |
| One nested group | Dotted keys | Structure on the key line itself |
| A group with many keys | A table header | Keys listed once under the header |
| Repeated groups of the same shape | [[name]] array of tables |
One dictionary per header, in file order |
| Text with backslashes, such as a path | Literal string | No escapes to double |
| Long text over several lines | Multiline string | Newlines kept, first one trimmed |
| A mask or flag value | Hex, octal, or binary integer | The base that matches the meaning |
Checklist
- Open TOML files in binary mode (
"rb") forload; useloadsfor a string already in memory. - Read the result as plain data: tables are dictionaries, arrays and arrays of tables are lists.
- Expect the date and time forms to arrive as
datetime,date, andtimeobjects, not strings. - Define each name once: a dotted key and a header cannot both claim the same table.
- Use literal strings for paths and other backslash text, so no escape is read by mistake.
- Keep underscores between digits only, in integers and floats alike.
- Catch
TOMLDecodeErroraround files the program does not control, and treat a failed parse as no result.
Related guides on this site
- Python JSON — dumps and loads — the other standard-library parser, with the writer side
tomllibdoes not have. - Python files — open, read, and write — the file modes, including the binary mode
loadneeds. - Python datetime — dates, times, and timedelta — working with the date and time values a TOML file produces.
Sources
- Python Standard Library,
tomllib—load,loads,TOMLDecodeError, the conversion table, and the binary-mode rule.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.