Tomllib parses TOML into Python values; parsing does not enforce an application configuration schema.
Python tomllib: parse configuration and validate its schema
Operation contract
The dispatch file supplies an exact field set, one known region and a bounded worker count. The schema rejects a TOML boolean for workers even though Python considers bool an int subclass. Keeping parser errors separate from domain errors helps distinguish malformed files from well-formed unsupported configuration.
Failure and ownership boundary
Tomllib.loads consumes text; load expects a binary file. Neither writes TOML. The fixture bounds text length before parsing, but a real file read must enforce a byte budget before materializing it. Configuration strings may contain secrets, so validation failures should name a field without echoing its value. Python configuration precedence: merge, validate, then publish and Python logging: allowlist fields before they reach a handler extend this contract.
Working program
import tomllib
def dispatch_config(text):
if len(text) > 1024:
raise ValueError("configuration budget exceeded")
parsed = tomllib.loads(text)
if set(parsed) != {"region", "workers"}:
raise ValueError("unexpected configuration fields")
if parsed["region"] not in {"DEL", "BOM"}:
raise ValueError("unknown region")
if type(parsed["workers"]) is not int or not 1 <= parsed["workers"] <= 8:
raise ValueError("workers must be an integer from 1 to 8")
return parsed
print(dispatch_config('region="DEL"\nworkers=3'))
try:
dispatch_config('region="DEL"\nworkers=true')
except ValueError:
print("boolean worker count rejected")Output
{'region': 'DEL', 'workers': 3}
boolean worker count rejectedCosts and limits
Parsing and validation retain the parsed document, with work dependent on input shape. A pre-read byte limit, depth policy and supported field types matter more than assuming a tiny final dictionary means the original document was cheap.
Common Mistakes
- Successful TOML parsing is not schema validation.
- Do not print a full configuration when a field is rejected.
Connected lessons
Python configuration precedence: merge, validate, then publish, Python JSON validation: reject duplicate members and non-integer amounts, Python logging: allowlist fields before they reach a handler.
