Python TOML Configuration
Learn how to read TOML configuration data with Python's tomllib module.
Intermediate
TOML is a configuration format designed to be easy for humans to read. Python's tomllib module parses TOML 1.0.0 into ordinary Python values. Unlike JSON and CSV lessons, this topic is about reading configuration data; tomllib does not provide a TOML writer.
Parse TOML text
Use tomllib.loads() when the TOML document is already a Python string. The result is a dictionary containing the parsed configuration data.
import tomllib
toml_text = """
name = "Foxipa"
port = 8080
enabled = true
"""
config = tomllib.loads(toml_text)
print(config["name"])
print(config["port"])
print(config["enabled"])Read a TOML file
Use tomllib.load() with a readable binary file object. The official API expects a binary file for file-based parsing, so open the TOML file with mode rb.
from pathlib import Path
import tempfile
import tomllib
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "config.toml"
path.write_bytes(b'name = "Foxipa"\nport = 8080\n')
with path.open("rb") as file:
config = tomllib.load(file)
print(config)TOML values become Python values
TOML has strings, integers, floats, booleans, arrays, tables, and date/time types. tomllib converts these into corresponding Python values such as str, int, float, bool, list, dict, and datetime objects.
import tomllib
toml_text = """
name = "Foxipa"
port = 8080
features = ["python", "css"]
enabled = true
[owner]
name = "Ada"
"""
config = tomllib.loads(toml_text)
print(type(config["port"]).__name__)
print(config["features"])
print(config["owner"]["name"])Use parsed configuration
After parsing, work with the returned dictionary rather than repeatedly parsing the document. Keep configuration data separate from the program logic that consumes it.
import tomllib
config = tomllib.loads("""
[server]
host = "localhost"
port = 8000
""")
server = config["server"]
print(f"Serving on {server["host"]}:{server["port"]}")Control TOML float conversion
tomllib.load() and tomllib.loads() accept parse_float. It receives the text of each TOML float and can convert it to another numeric type, such as decimal.Decimal.
from decimal import Decimal
import tomllib
config = tomllib.loads("price = 19.95", parse_float=Decimal)
print(config["price"])
print(type(config["price"]).__name__)Handle invalid TOML
Invalid TOML raises tomllib.TOMLDecodeError. Handle that exception when configuration input may be malformed, and report a useful error rather than assuming parsing succeeded.
import tomllib
try:
tomllib.loads("port = [8000")
except tomllib.TOMLDecodeError as error:
print("Invalid TOML:", error)TOML and other data formats
Use TOML when you need a human-oriented configuration format and Python only needs to read the document with the standard library. JSON is a general structured-data interchange format, while CSV is designed for tabular rows. TOML is not a replacement for either one.
Remember the ownership boundary: File I/O opens the file and supplies a stream; tomllib interprets TOML and returns Python data. The standard-library tomllib module does not write TOML files.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.