Reading TOML config files with tomllib
suggest changeTOML is a config file format. It looks like an INI file, but values have real types: strings must be quoted, and there are integers, floats, booleans, dates, arrays and nested tables. Python projects already use it for pyproject.toml, and many tools (Ruff, pytest, mypy, Black, uv) read their settings from there.
Python 3.11 added the tomllib module to the standard library (PEP 680). It is a copy of the third-party tomli parser. It can only read TOML. To write it you need a package such as tomli-w.
| Version | Change |
|---|---|
| 3.11 | tomllib added, with load(), loads() and TOMLDecodeError |
| 3.14 | TOMLDecodeError has msg, doc, pos, lineno and colno attributes |
| older | install tomli from PyPI, which has the same API |
All examples were run with Python 3.13, except the ones marked 3.14. The writing examples use tomli-w 1.2.0 and the TOML 1.1 example uses tomli 2.5.0.
Reading a file
Here is a config.toml:
# Application settings
title = "Inventory service"
debug = false
[server]
host = "127.0.0.1"
port = 8443
workers = 4
[database]
url = "postgresql://localhost/inventory"
pool_size = 10
timeout = 2.5
[logging]
level = "info"
handlers = ["console", "file"]
tomllib.load() reads it from a file object and returns a plain dict. Each [section] becomes a nested dict:
import tomllib
with open("config.toml", "rb") as f:
config = tomllib.load(f)
print(type(config))
print(config["title"])
print(config["server"])
print(config["server"]["port"] + 1)
print(config["logging"]["handlers"])
<class 'dict'>
Inventory service
{'host': '127.0.0.1', 'port': 8443, 'workers': 4}
8444
['console', 'file']
port is already an int and handlers is already a list. You don't have to convert anything, which is the main advantage over INI files.
The file must be opened in binary mode
Note the "rb". TOML files are always UTF-8, so tomllib decodes the bytes itself. That way the result doesn't depend on the platform's default encoding (on Windows it is often not UTF-8). If you pass a file opened in text mode, you get an error:
import tomllib
with open("config.toml") as f: # text mode
try:
tomllib.load(f)
except TypeError as e:
print("TypeError:", e)
TypeError: File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`
Any binary file object works, including io.BytesIO.
Parsing a string with loads
tomllib.loads() parses a str. Use it when the TOML text comes from somewhere other than a file, or when you already read the file with pathlib:
import tomllib
text = """
name = "demo"
version = "1.4.0"
[features]
cache = true
retries = 3
"""
data = tomllib.loads(text)
print(data)
{'name': 'demo', 'version': '1.4.0', 'features': {'cache': True, 'retries': 3}}
from pathlib import Path
import tomllib
config = tomllib.loads(Path("config.toml").read_text(encoding="utf-8"))
print(config["database"]["url"])
postgresql://localhost/inventory
loads() needs a str, and load() needs a binary file. Mixing them up raises TypeError. In 3.13 the message for loads(b"...") is confusing:
import io
import tomllib
data = 'city = "Kraków"\n'.encode("utf-8")
print(tomllib.load(io.BytesIO(data)))
print(tomllib.loads(data.decode()))
try:
tomllib.loads(data)
except TypeError as e:
print("TypeError:", e)
{'city': 'Kraków'}
{'city': 'Kraków'}
TypeError: a bytes-like object is required, not 'str'
Python 3.14 says what is wrong: TypeError: Expected str object, not 'bytes'.
How TOML types map to Python types
| TOML | Python |
|---|---|
string (basic "...", literal '...', multi-line) |
str |
integer (also hex, octal, binary, 1_000) |
int |
float (also inf, nan) |
float |
| boolean | bool |
| offset date-time | datetime.datetime with tzinfo |
| local date-time | datetime.datetime without tzinfo |
| local date | datetime.date |
| local time | datetime.time |
| array | list |
| table, inline table | dict |
| array of tables | list of dict |
import tomllib
doc = tomllib.loads(r'''
string = "tab:\there"
literal = 'C:\temp\app'
multiline = """
first line
second line"""
integer = 1_000_000
hex = 0xff
float = 6.02e23
infinity = inf
boolean = true
offset_dt = 2026-10-18T09:30:00+02:00
utc_dt = 2026-10-18T07:30:00Z
local_dt = 2026-10-18T09:30:00
local_date = 2026-10-18
local_time = 09:30:00.250
array = [1, 2, 3]
mixed = [1, "two", 3.0]
inline = { x = 1, y = 2 }
''')
for key, value in doc.items():
print(f"{key:<10} {type(value).__name__:<9} {value!r}")
string str 'tab:\there'
literal str 'C:\\temp\\app'
multiline str 'first line\nsecond line'
integer int 1000000
hex int 255
float float 6.02e+23
infinity float inf
boolean bool True
offset_dt datetime datetime.datetime(2026, 10, 18, 9, 30, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200)))
utc_dt datetime datetime.datetime(2026, 10, 18, 7, 30, tzinfo=datetime.timezone.utc)
local_dt datetime datetime.datetime(2026, 10, 18, 9, 30)
local_date date datetime.date(2026, 10, 18)
local_time time datetime.time(9, 30, 0, 250000)
array list [1, 2, 3]
mixed list [1, 'two', 3.0]
inline dict {'x': 1, 'y': 2}
The Python string is wrapped in r'''...''' so that Python passes the backslashes to TOML unchanged. In the TOML basic string "tab:\there", \t became a real tab character. In the literal string 'C:\temp\app', the backslashes were kept, which is handy for Windows paths and regular expressions. Arrays can mix types (this is allowed since TOML 1.0). TOML has no null value, so you never get None.
Keys keep the order they have in the file, because the result is an ordinary dict.
Tables, dotted keys and arrays of tables
Nested data can be written in three ways. Dotted keys and [a.b] headers create nested dicts. [[name]] adds one more dict to a list each time it appears:
import tomllib
from pprint import pprint
doc = tomllib.loads('''
site.name = "shop"
site.owner.email = "admin@example.com"
[servers.alpha]
ip = "10.0.0.1"
[servers.beta]
ip = "10.0.0.2"
[[products]]
name = "Hammer"
sku = 738594937
[[products]]
name = "Nail"
sku = 284758393
color = "gray"
''')
pprint(doc, sort_dicts=False)
for p in doc["products"]:
print(p["name"], p.get("color", "-"))
{'site': {'name': 'shop', 'owner': {'email': 'admin@example.com'}},
'servers': {'alpha': {'ip': '10.0.0.1'}, 'beta': {'ip': '10.0.0.2'}},
'products': [{'name': 'Hammer', 'sku': 738594937},
{'name': 'Nail', 'sku': 284758393, 'color': 'gray'}]}
Hammer -
Nail gray
Parsing floats as Decimal
Both functions take a parse_float argument. It is called with the text of every TOML float, and its result is used as the value. Pass decimal.Decimal when you need exact values, for example for money:
import tomllib
from decimal import Decimal
text = "price = 19.99\ntax = 0.23\n"
print(tomllib.loads(text))
prices = tomllib.loads(text, parse_float=Decimal)
print(prices)
print(prices["price"] * (1 + prices["tax"]))
{'price': 19.99, 'tax': 0.23}
{'price': Decimal('19.99'), 'tax': Decimal('0.23')}
24.5877
parse_float is used only for floats; integers are always int. It also can't return a dict or a list:
import tomllib
try:
tomllib.loads("x = 1.5", parse_float=lambda s: {"value": s})
except ValueError as e:
print("ValueError:", e)
ValueError: parse_float must not return dicts or lists
Handling invalid TOML
Invalid documents raise tomllib.TOMLDecodeError, which is a subclass of ValueError. The message includes the line and column:
import tomllib
bad = '''
[server]
host = "localhost"
port = 80 80
'''
try:
tomllib.loads(bad)
except tomllib.TOMLDecodeError as e:
print("Invalid TOML:", e)
print(isinstance(e, ValueError))
for text in ['a = 1\na = 2', 'name = hello', 'when = 2026-13-01', '[t]\n[t]']:
try:
tomllib.loads(text)
except tomllib.TOMLDecodeError as e:
print(f"{text!r:22} -> {e}")
Invalid TOML: Expected newline or end of document after a statement (at line 4, column 11)
True
'a = 1\na = 2' -> Cannot overwrite a value (at end of document)
'name = hello' -> Invalid value (at line 1, column 8)
'when = 2026-13-01' -> Expected newline or end of document after a statement (at line 1, column 12)
'[t]\n[t]' -> Cannot declare ('t',) twice (at line 2, column 3)
TOML is strict, which is good for config files: a key can't be defined twice, a table can't be declared twice, and strings must be quoted. Some messages describe what the parser saw rather than what you got wrong. An invalid month in a date gives the generic "Expected newline" error above.
In Python 3.14 the exception also has the details as attributes, so you can show the bad line to the user:
import sys
import tomllib
print(sys.version_info[:2])
try:
tomllib.loads('[server]\nport = 80 80\n')
except tomllib.TOMLDecodeError as e:
print(repr(e.msg))
print(e.lineno, e.colno, e.pos)
print(repr(e.doc.splitlines()[e.lineno - 1]))
(3, 14)
'Expected newline or end of document after a statement'
2 11 19
'port = 80 80'
pos is the index of the error in doc, the string that was parsed. On 3.13 and older these attributes don't exist and you get an AttributeError.
Because a parse error is just an exception, checking that every TOML file in a project is valid makes a simple test. The subtests example in Parameterized tests does exactly that.
Reading pyproject.toml
pyproject.toml is a normal TOML file. The standard tables are [build-system] and [project], and every tool keeps its own settings under [tool.<name>]:
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "inventory"
version = "0.3.1"
requires-python = ">=3.11"
dependencies = [
"httpx>=0.27",
"pydantic>=2.7",
]
[project.optional-dependencies]
dev = ["pytest>=8", "ruff"]
[project.scripts]
inventory = "inventory.cli:main"
[tool.ruff]
line-length = 100
[tool.inventory]
default-region = "eu-central"
max-items = 500
import tomllib
from pathlib import Path
with Path("pyproject.toml").open("rb") as f:
pyproject = tomllib.load(f)
project = pyproject["project"]
print(project["name"], project["version"])
print("Python:", project["requires-python"])
for dep in project["dependencies"]:
print(" needs", dep)
print("extras:", list(project.get("optional-dependencies", {})))
print("ruff line length:", pyproject.get("tool", {}).get("ruff", {}).get("line-length"))
# settings for our own tool live under [tool.<name>]
settings = pyproject.get("tool", {}).get("inventory", {})
print(settings)
inventory 0.3.1
Python: >=3.11
needs httpx>=0.27
needs pydantic>=2.7
extras: ['dev']
ruff line length: 100
{'default-region': 'eu-central', 'max-items': 500}
Keys with dashes such as requires-python are normal string keys, so you can't use attribute-style access on them. Most tables are optional, which is why the code uses .get(..., {}).
Command line tools usually look for pyproject.toml in the current directory and then in each parent directory, so they also work when you run them from a subdirectory of the project:
import tomllib
from pathlib import Path
def find_pyproject(start: Path) -> Path | None:
for directory in [start, *start.parents]:
candidate = directory / "pyproject.toml"
if candidate.is_file():
return candidate
return None
def load_tool_config(name: str, start: Path | None = None) -> dict:
path = find_pyproject((start or Path.cwd()).resolve())
if path is None:
return {}
with path.open("rb") as f:
return tomllib.load(f).get("tool", {}).get(name, {})
sub = Path("src/inventory")
sub.mkdir(parents=True, exist_ok=True)
print(load_tool_config("inventory", start=sub))
print(load_tool_config("missing", start=sub))
{'default-region': 'eu-central', 'max-items': 500}
{}
To read the installed version of a package, use importlib.metadata.version("inventory"), not pyproject.toml. The file usually isn't included when the package is installed.
Defaults and validation
tomllib only checks that the file is valid TOML. It doesn't know which keys your program expects. A common pattern is to merge the user's file over a dict of defaults:
import tomllib
DEFAULTS = {
"debug": False,
"server": {"host": "0.0.0.0", "port": 8000, "workers": 1},
"logging": {"level": "warning", "handlers": ["console"]},
}
def deep_merge(base: dict, override: dict) -> dict:
result = dict(base)
for key, value in override.items():
if isinstance(value, dict) and isinstance(result.get(key), dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
user = tomllib.loads('''
debug = true
[server]
port = 9000
''')
config = deep_merge(DEFAULTS, user)
print(config)
{'debug': True, 'server': {'host': '0.0.0.0', 'port': 9000, 'workers': 1}, 'logging': {'level': 'warning', 'handlers': ['console']}}
Instead of passing nested dicts around, you can load the config into dataclasses. The field defaults are the default settings, unknown keys are rejected by __init__, and a small check catches values of the wrong type:
import tomllib
from dataclasses import dataclass, field, fields
@dataclass(frozen=True)
class ServerConfig:
host: str = "127.0.0.1"
port: int = 8000
workers: int = 1
@dataclass(frozen=True)
class AppConfig:
title: str
debug: bool = False
server: ServerConfig = field(default_factory=ServerConfig)
def check_types(obj) -> None:
for f in fields(obj):
value = getattr(obj, f.name)
expected = f.type if isinstance(f.type, type) else object
# bool is a subclass of int, so reject it explicitly for int fields
if not isinstance(value, expected) or (expected is int and isinstance(value, bool)):
raise TypeError(f"{type(obj).__name__}.{f.name}: expected "
f"{expected.__name__}, got {value!r}")
def load_config(text: str) -> AppConfig:
raw = tomllib.loads(text)
server = ServerConfig(**raw.pop("server", {}))
check_types(server)
config = AppConfig(**raw, server=server)
check_types(config)
return config
print(load_config('title = "demo"\n[server]\nport = 9000\n'))
for text in ['title = "demo"\n[server]\nport = "9000"\n',
'title = "demo"\ncolour = "blue"\n']:
try:
load_config(text)
except TypeError as e:
print("error:", e)
AppConfig(title='demo', debug=False, server=ServerConfig(host='127.0.0.1', port=9000, workers=1))
error: ServerConfig.port: expected int, got '9000'
error: AppConfig.__init__() got an unexpected keyword argument 'colour'
check_types only handles plain classes such as int and str. f.type is the class itself only when the module doesn't use from __future__ import annotations. For bigger configs, a validation library such as Pydantic or msgspec does all of this, including nested models and error messages that list every problem.
If you only want type checker support and no runtime checks, describe the config with a TypedDict and cast() the result of tomllib.load() to it.
Writing TOML with tomli-w
tomllib has no dump() or dumps(). The standard library leaves writing out on purpose, because a writer has to make style choices (inline tables or [headers], how to format arrays, and what to do with comments), and there is no single right answer. The tomli-w package (pip install tomli-w) is the matching writer:
import tomllib
from datetime import date
import tomli_w
config = {
"title": "Inventory service",
"released": date(2026, 10, 18),
"server": {"host": "127.0.0.1", "port": 8443},
"products": [
{"name": "Hammer", "sku": 738594937},
{"name": "Nail", "sku": 284758393},
],
}
text = tomli_w.dumps(config)
print(text)
print(tomllib.loads(text) == config)
with open("out.toml", "wb") as f: # binary mode, like tomllib.load
tomli_w.dump(config, f)
title = "Inventory service"
released = 2026-10-18
products = [
{ name = "Hammer", sku = 738594937 },
{ name = "Nail", sku = 284758393 },
]
[server]
host = "127.0.0.1"
port = 8443
True
tomli-w writes a list of dicts as an array of inline tables, not as [[products]]. Both forms parse to the same data, so the round trip compares equal. Like tomllib.load(), tomli_w.dump() works with binary files and always writes UTF-8.
Two options change the formatting: multiline_strings=True writes strings that contain newlines as """ strings, and indent sets the indentation of arrays:
import tomli_w
data = {"motd": "Welcome!\nBe nice.", "ports": [80, 443]}
print(tomli_w.dumps(data))
print(tomli_w.dumps(data, multiline_strings=True, indent=2))
motd = "Welcome!\nBe nice."
ports = [
80,
443,
]
motd = """
Welcome!
Be nice."""
ports = [
80,
443,
]
Comments are lost
tomllib returns plain dicts, and comments are not part of the data. If you load a file, change a value and write it back, the comments are gone. Values that TOML can't represent, such as None, raise TypeError:
import tomllib
import tomli_w
original = '''# Server settings
[server]
port = 8443 # HTTPS
host = "127.0.0.1"
'''
data = tomllib.loads(original)
data["server"]["port"] = 9443
print(tomli_w.dumps(data))
try:
tomli_w.dumps({"password": None})
except TypeError as e:
print("TypeError:", e)
[server]
port = 9443
host = "127.0.0.1"
TypeError: Object of type 'NoneType' is not TOML serializable
If your program has to edit a file written by a person, for example to bump a version in pyproject.toml, use the tomlkit package. It keeps comments, whitespace and key order when you change a value.
Supporting Python 3.10 and older
tomli is the package tomllib was copied from, and it has the same API. To support older Pythons, add a conditional dependency in pyproject.toml:
dependencies = [
'tomli>=1.1.0; python_version < "3.11"',
]
and import whichever is available:
import sys
if sys.version_info >= (3, 11):
import tomllib
else:
import tomli as tomllib
print(tomllib.__name__)
print(tomllib.loads('answer = 42'))
tomllib
{'answer': 42}
A try: import tomllib / except ImportError: import tomli as tomllib block works too. The sys.version_info check is better because type checkers such as mypy and pyright understand it and only check the branch for the target version.
TOML 1.1
tomllib in Python 3.11 to 3.14 implements TOML 1.0. Recent versions of tomli (2.4 and newer) also accept the additions from TOML 1.1: newlines and trailing commas in inline tables, times without seconds and the \e escape. A file that uses them can be read by tomli but not by tomllib:
import tomllib
import tomli
samples = [
"point = {\n x = 1,\n y = 2,\n}", # multi-line inline table, trailing comma
"alarm = 07:30", # time without seconds
r'bold = "\e[1m"', # \e escape
]
for text in samples:
for parser in (tomllib, tomli):
try:
result = parser.loads(text)
except parser.TOMLDecodeError as e:
result = f"error: {e}"
print(f"{parser.__name__:<8} {result}")
tomllib error: Invalid initial character for a key part (at line 1, column 10)
tomli {'point': {'x': 1, 'y': 2}}
tomllib error: Expected newline or end of document after a statement (at line 1, column 10)
tomli {'alarm': datetime.time(7, 30)}
tomllib error: Unescaped '\' in a string (at line 1, column 11)
tomli {'bold': '\x1b[1m'}
If other programs read your config files too, stick to TOML 1.0 syntax for now.
tomllib compared with configparser
configparser reads INI files and has been in the standard library much longer. The same settings in both formats:
[server]
host = 127.0.0.1
port = 8443
debug = no
handlers = console, file
[server]
host = "127.0.0.1"
port = 8443
debug = false
handlers = ["console", "file"]
import configparser
import tomllib
ini = configparser.ConfigParser()
ini.read("settings.ini")
server = ini["server"]
print(repr(server["port"]), repr(server["debug"]), repr(server["handlers"]))
print(server.getint("port"), server.getboolean("debug"),
[h.strip() for h in server["handlers"].split(",")])
with open("settings.toml", "rb") as f:
server = tomllib.load(f)["server"]
print(repr(server["port"]), repr(server["debug"]), repr(server["handlers"]))
'8443' 'no' 'console, file'
8443 False ['console', 'file']
8443 False ['console', 'file']
configparser returns every value as a string, and you convert it yourself with getint(), getboolean() or your own code. With TOML the types are written in the file.
| configparser (INI) | tomllib (TOML) | |
|---|---|---|
| Value types | always str, convert with getint() and friends |
str, int, float, bool, dates, lists, dicts |
| Nesting | one level of sections | any depth |
| Lists | no, split strings yourself | arrays |
| Writing | yes, ConfigParser.write() |
no, use tomli-w or tomlkit |
| Keys | case-insensitive by default | case-sensitive |
| Duplicate keys | error by default (strict=True) |
always an error |
| Extras | [DEFAULT] section, %(name)s interpolation |
none |
| Specification | none, formats vary between programs | toml.io |
Use TOML for new config files, especially in Python projects that already have a pyproject.toml. configparser is still useful when you need to read or write existing INI files, or when your program has to save settings without extra packages.
Summary
tomllib.load(f)needs a file opened in binary mode ("rb").tomllib.loads(s)takes astr.- The result is a plain
dictwith real Python types. Dates and times becomedatetimeobjects. There is noNone. parse_float=Decimalgives exact decimal values.- Errors raise
tomllib.TOMLDecodeError, aValueError. In 3.14 it haslineno,colnoand other attributes. tomllibdoesn't check which keys you expect. Merge with defaults or load into dataclasses or a validation library.- To write TOML, use
tomli-w. To edit files and keep comments, usetomlkit. - On Python 3.10 and older, use
tomli. It has the same API.