How to Parse TOML in Python 3.11 Using tomllib
Python 3.11 introduced tomllib to the standard library,
providing native support for parsing TOML (Tom's Obvious, Minimal
Language) documents without third-party dependencies. This article
explains how tomllib works, demonstrates how to parse TOML
from strings and files, details how TOML data types map to Python native
types, and covers error handling and module limitations.
Loading TOML from Files and Strings
The tomllib module provides two primary functions for
parsing: load() for reading binary streams and
loads() for parsing string inputs.
Unlike standard text parsers that accept plain text file streams,
tomllib.load() requires the file to be opened in binary
read mode ("rb"). This requirement ensures strict adherence
to the TOML specification, which mandates UTF-8 encoding.
import tomllib
# Reading from a TOML file
with open("config.toml", "rb") as f:
config = tomllib.load(f)
print(config)To parse a TOML document that is already loaded in memory as a
string, use tomllib.loads():
import tomllib
toml_string = """
[database]
server = "192.168.1.1"
ports = [ 8000, 8001, 8002 ]
connection_max = 5000
enabled = true
"""
data = tomllib.loads(toml_string)
print(data["database"]["server"]) # Output: 192.168.1.1Type Mapping
tomllib automatically translates TOML specifications
into corresponding native Python data structures:
- Tables and Inline Tables: Convert to standard
Python
dictobjects. - Arrays: Convert to Python
listobjects, including nested arrays and arrays of tables. - Strings: Convert to
str. - Integers and Floats: Convert to Python
intandfloat. You can optionally passparse_floattoload()orloads()to customize float parsing (for example, usingdecimal.Decimal). - Booleans: Convert to
bool(TrueorFalse). - Dates and Times: Parse directly into
datetime.date,datetime.time, or timezone-awaredatetime.datetimeobjects depending on the TOML format used.
Customizing Float Parsing
By default, floating-point numbers are converted to Python
float instances. To preserve exact precision, such as when
dealing with financial data, configure the parser to use
decimal.Decimal:
from decimal import Decimal
import tomllib
toml_data = 'price = 19.99'
parsed = tomllib.loads(toml_data, parse_float=Decimal)
print(type(parsed["price"])) # Output: <class 'decimal.Decimal'>Error Handling
When given invalid syntax, tomllib raises a
tomllib.TOMLDecodeError. This exception indicates
formatting issues such as unclosed quotes, duplicate table definitions,
or type mismatches:
import tomllib
invalid_toml = """
[server]
port = "unclosed string
"""
try:
tomllib.loads(invalid_toml)
except tomllib.TOMLDecodeError as e:
print(f"Failed to parse TOML: {e}")Read-Only Design
The tomllib module is strictly a parser and does not
include functionality to write or serialize Python dictionaries back
into TOML format (there is no dump() or
dumps() function). If an application requires generating or
modifying TOML files, external libraries such as tomli-w or
tomlkit must be used.