Python Tomllib Module
The tomllib module parses TOML configuration files from Python.
The module was added in Python 3.11. It is read-only, so use it for parsing TOML rather than writing it.
import tomllib
TOML is commonly used for configuration files such as pyproject.toml. It looks like simple key-value pairs and sections.
Parsing TOML from a string
loads parses a TOML document stored in a string.
import tomllib
config = tomllib.loads("""
name = "python-cheatsheet"
version = "1.0"
[database]
port = 5432
""")
print(config['name'])
print(config['database']['port'])
python-cheatsheet
5432
TOML values are converted to Python values:
import tomllib
config = tomllib.loads("""
debug = true
ports = [8000, 8001]
""")
print(config['debug'])
print(config['ports'])
True
[8000, 8001]
Reading a TOML file
load expects a binary file object.
import tomllib
from io import BytesIO
data = b'name = "demo"'
config = tomllib.load(BytesIO(data))
print(config)
{'name': 'demo'}
If you open a real file, use binary mode:
import tomllib
with open('pyproject.toml', 'rb') as file:
config = tomllib.load(file)