pyguides

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 typePython type
stringstr
integerint
floatfloat (or custom via parse_float)
booleanbool
offset date-timedatetime.datetime (with tzinfo)
local date-timedatetime.datetime (tzinfo = None)
local datedatetime.date
local timedatetime.time
inline tabledict
array of tableslist 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

PackageReadingWritingPreserves stylePython version
tomllib (stdlib)YesNoN/A3.11+
tomli (PyPI)YesNoNo3.7+
tomlkit (PyPI)YesYesYesAll

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.toml files in Python projects