Load Typed Configuration with TOML
Core idea
TOML is a configuration format supporting typed values and tables. Python 3.11+ provides tomllib for reading TOML: loads accepts a string and load accepts a binary file. There is no built-in TOML writer in tomllib.
import tomllibconfig = tomllib.loads("[service]\nport = 8080\nenabled = true\n")print(config["service"]["port"], config["service"]["enabled"])Table fields become a nested dictionary with integer and Boolean values.
Read a binary configuration file
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) import tomllib p = root / "settings.toml" p.write_bytes(b"retries = 3\n") with p.open("rb") as f: data = tomllib.load(f) print(data["retries"] + 1)load reads a binary stream and parses the numeric value.
Common mistake
Do not assume successful parsing validates business rules. A parsed port still needs a range check, and required fields need validation. Limit input size and catch TOMLDecodeError for invalid syntax.
Practice
Parse a table with retries and enabled; require retries to be a nonnegative integer (excluding bool) and enabled to be a Boolean.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
TOML types
Check your understanding of toml reading.
What is printed?
import tomllibprint(type(tomllib.loads("n = 2")["n"]).__name__)What is printed?
import tomllibfrom io import BytesIOprint(tomllib.load(BytesIO(b"flag = false"))["flag"])Which operation is unsupported by tomllib?
What should happen after parsing configuration?