A configuration file can be valid TOML and still be wrong for the program that reads it. A port might be written as a string, a worker count might be zero, or a misspelled option might silently leave a default in place. This example uses Python's standard library to parse a small server configuration and check its application rules before returning a typed object.
Download the complete TOML configuration project. The ZIP includes the CLI, a sample file, thirteen tests and a README. The exercise prints the validated settings so you can inspect the result.
Create a small configuration file
Use Python 3.11 or later. The tomllib module is included from that version, and this project needs no additional packages. Put the following text in sample.toml in the same folder as the Python files. Use python3 in the commands if that is how your system starts Python.
[server]
port = 8080
workers = 4
debug = false
The rules for this example are deliberately small. The file must have exactly one server table. It must specify an integer port between 1 and 65535. The optional workers setting accepts integers from 1 to 16 and defaults to 2. The optional debug setting accepts a boolean and defaults to false. Unknown keys produce an error so a typo such as workres cannot quietly select the worker default.
Parse the file and validate each field
Save this as config.py. It reads at most 16 KiB plus one byte, checks the limit, decodes UTF-8 and passes the text to tomllib.loads. The parser checks TOML syntax and produces Python values. The following checks then apply the example's field and range rules. The returned frozen dataclass groups the validated values for its caller.
import argparse
from dataclasses import dataclass
from pathlib import Path
import tomllib
MAX_CONFIG_BYTES = 16 * 1024
@dataclass(frozen=True)
class ServerConfig:
port: int
workers: int
debug: bool
def load_config(path: Path) -> ServerConfig:
with path.open("rb") as source:
raw = source.read(MAX_CONFIG_BYTES + 1)
if len(raw) > MAX_CONFIG_BYTES:
raise ValueError("configuration must be 16 KiB or smaller")
document = tomllib.loads(raw.decode("utf-8"))
if set(document) != {"server"} or not isinstance(document["server"], dict):
raise ValueError("configuration must contain only a [server] table")
server = document["server"]
unknown = set(server) - {"port", "workers", "debug"}
if unknown:
raise ValueError("unknown server setting: " + ", ".join(sorted(unknown)))
port = server.get("port")
workers = server.get("workers", 2)
debug = server.get("debug", False)
if type(port) is not int or not 1 <= port <= 65535:
raise ValueError("server.port must be an integer from 1 to 65535")
if type(workers) is not int or not 1 <= workers <= 16:
raise ValueError("server.workers must be an integer from 1 to 16")
if type(debug) is not bool:
raise ValueError("server.debug must be true or false")
return ServerConfig(port=port, workers=workers, debug=debug)
def main() -> None:
parser = argparse.ArgumentParser(description="Validate a small TOML server configuration.")
parser.add_argument("config", type=Path, help="path to a TOML file")
args = parser.parse_args()
try:
config = load_config(args.config)
except (OSError, ValueError) as error:
parser.error(str(error))
print(f"port={config.port} workers={config.workers} debug={str(config.debug).lower()}")
if __name__ == "__main__":
main()
Notice the integer check uses type(value) is int. In Python, bool is a subclass of int, so isinstance(True, int) is true. A simple integer instance check could therefore accept port = true. Here, exact type checks distinguish the integer settings from the boolean setting. Quoted digits such as port = "8080" also produce an error because TOML parses them as a string.
Run the CLI and check its result
python config.py sample.toml
python -m unittest -v
The sample produces one output line and exits with status 0.
port=8080 workers=4 debug=false
If a file cannot be read, contains invalid UTF-8, has malformed TOML or fails the setting rules, parser.error prints a usage message and the reason to standard error, then exits with status 2. A calling script can inspect that status before proceeding. Keep the file path explicit when running from another directory because relative paths are resolved from the terminal's current directory.
Try the failure cases
| Change | Expected outcome |
|---|---|
| Set port to true or "8080" | Port must be an integer |
| Set workers to 0 or 17 | Worker count must be within 1 to 16 |
| Set debug to "false" | Debug must be a boolean |
| Write workres instead of workers | The unknown setting is named in the error |
| Remove the workers and debug lines | Defaults of 2 and false are used |
| Break the table's closing bracket | TOML syntax error and exit 2 |
Run python -m unittest -v from the extracted folder to exercise these cases and the file errors. The tests also check that a successful CLI run preserves the input file and prints the exact expected result. Parser error wording can vary by Python release, so the malformed-file test checks the error outcome without depending on the complete message.
Adapt the rules to your application
When adding a setting, update the allowed keys, validation, returned object and tests together. Defaults should apply to omitted optional settings; explicit wrong values should give the user a chance to fix the file. A valid port number still needs a separate runtime check if your application will bind a socket. The sample worker bounds are its own application rule, which you can change to match the program that consumes the configuration.
References include Python's TOML parser, the boolean type and argparse error handling.
Comments (0)
Join the discussion