tomllib module
tomllib reads TOML 1.0.0 files and strings into Python dictionaries. It’s part of the standard library in Python 3.11, and before that you needed the tomli pip package. tomllib is read-only — it has no dump or dumps functions.
Functions
tomllib.load(fp, /, *, parse_float=float)
Read TOML from a binary file object and return a dict.
import tomllib
with open("config.toml", "rb") as f:
data = tomllib.load(f)
The file must be opened in binary mode ("rb"), not text mode. The parse_float keyword argument lets you replace the float parser — by default TOML floats become Python float, but you can use decimal.Decimal instead:
from decimal import Decimal
import tomllib
with open("config.toml", "rb") as f:
data = tomllib.load(f, parse_float=Decimal)
tomllib.loads(s, /, *, parse_float=float)
Parse TOML from a string and return a dict:
import tomllib
toml_string = """
[settings]
name = "myapp"
version = 2
sugar_free = true
[settings.database]
host = "localhost"
"""
data = tomllib.loads(toml_string)
print(data["settings"]["name"]) # "myapp"
print(data["settings"]["sugar_free"]) # True
print(data["settings"]["database"]["host"]) # "localhost"
TOML to Python Type Conversion
| TOML type | Python type |
|---|---|
| string | str |
| integer | int |
| float | float (or custom via parse_float) |
| boolean | bool |
| offset date-time | datetime.datetime (with tzinfo) |
| local date-time | datetime.datetime (tzinfo = None) |
| local date | datetime.date |
| local time | datetime.time |
| inline table | dict |
| array of tables | list of dict |
Handling Errors
tomllib raises tomllib.TOMLDecodeError on invalid TOML. It’s a subclass of ValueError with extra attributes for pinpointing the error:
import tomllib
try:
tomllib.loads("[invalid")
except tomllib.TOMLDecodeError as e:
print(f"Error on line {e.lineno}, column {e.colno}: {e.msg}")
# Error on line 1, column 2: ...
The error attributes are msg, doc, pos, lineno, and colno.
Why Binary Mode?
tomllib requires binary mode ("rb") because TOML parsers need to handle exact byte offsets for error reporting. Text-mode file objects don’t expose reliable byte positions.
If you have a string already, use tomllib.loads() instead.
tomllib vs tomli vs tomlkit
| Package | Reading | Writing | Preserves style | Python version |
|---|---|---|---|---|
tomllib (stdlib) | Yes | No | N/A | 3.11+ |
tomli (PyPI) | Yes | No | No | 3.7+ |
tomlkit (PyPI) | Yes | Yes | Yes | All |
tomlkit is the choice if you need to round-trip TOML files without losing comments or formatting.
See Also
- json module — JSON parsing (included in stdlib since Python always)
- pyproject-toml — working with
pyproject.tomlfiles in Python projects