Python Basics: Reading TOML Configuration with tomllib
TOML stores configuration as readable key-value pairs. Python’s standard-library tomllib parses it into dictionaries, lists, and other Python values.
Use Python 3.12 or newer on Linux. tomllib was added in Python 3.11 and reads TOML; it does not write TOML files.
Load a small configuration file
This script writes its sample configuration only inside a fresh temporary directory. Warning: leaving the TemporaryDirectory context removes that directory and its contents.
Save as demo_tomllib_1.py:
from pathlib import Path
from tempfile import TemporaryDirectory
import tomllib
with TemporaryDirectory() as directory:
path = Path(directory) / "settings.toml"
with path.open("x", encoding="utf-8") as file:
file.write('[app]\nname = "reporter"\nworkers = 3\ndebug = false\n')
with path.open("rb") as file:
config = tomllib.load(file)
app = config["app"]
print(app["name"])
print(app["workers"], type(app["workers"]).__name__)
print(app["debug"], type(app["debug"]).__name__)Run:
python3 demo_tomllib_1.pyOutput:
reporter
3 int
False boolload() expects a binary file opened with "rb". The [app] table becomes a nested dictionary. Mode "x" creates the sample exclusively rather than overwriting an existing file.
Check the shape your program needs
Valid TOML can still contain an unsuitable value. Parsing verifies syntax, not your application’s settings.
Save as demo_tomllib_2.py:
import tomllib
def read_workers(text):
config = tomllib.loads(text)
app = config.get("app", {})
if not isinstance(app, dict):
raise ValueError("app must be a table")
workers = app.get("workers", 2)
if type(workers) is not int or not 1 <= workers <= 8:
raise ValueError("workers must be an integer from 1 to 8")
return workers
for text in ('[app]\nworkers = 4', '[app]', '[app]\nworkers = true'):
try:
print("Workers:", read_workers(text))
except ValueError as error:
print(error)
try:
tomllib.loads('name = "unfinished')
except tomllib.TOMLDecodeError:
print("Invalid TOML")Run:
python3 demo_tomllib_2.pyOutput:
Workers: 4
Workers: 2
workers must be an integer from 1 to 8
Invalid TOMLloads() accepts a string. The exact type check rejects booleans because Python otherwise treats bool as a subclass of int. A missing file raises FileNotFoundError, separately from a TOML syntax error. Put a size limit on untrusted configuration before parsing it.
References
Acknowledgements
This post was created with assistance from AI.