Content · Programming · Python

Python Build a Configuration Validator

Validate configuration before using it to control an application.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Validate configuration before using it to control an application.

How It Works


Configuration validation should reject missing required fields, incorrect data types and values outside permitted ranges. Parse the data separately from checking business rules so error messages can identify the precise setting. Never print passwords as part of diagnostic output.

TOML validates document syntax, not whether the resulting settings are meaningful for your program.

Step-by-Step Example


import tomllib

settings = tomllib.loads('server = "localhost"\nport = 8080\n')
required = {"server", "port"}
missing = required - settings.keys()
if missing:
    raise ValueError(f"Missing settings: {sorted(missing)}")
if not isinstance(settings["port"], int) or not 1 <= settings["port"] <= 65535:
    raise ValueError("port must be a TCP port number")
print(settings["server"], settings["port"])

Understanding the Example


  • The expression 'tomllib.loads(\'server = "localhost"\\nport = 8080\\n\')' supplies the value stored as 'settings'. This value is then used or checked by the later statements.
  • The expression '{"server", "port"}' supplies the value stored as 'required'. This value is then used or checked by the later statements.

A successful run of this example prints the following output:

localhost 8080

Where This Fits in a Real Program


In a real import pipeline, parsing is only the first stage. Convert each field to the intended type, reject missing or unexpected values and report which record failed. Keep the original source file unchanged until the normalized data has passed validation and an export has been checked.

Practice: Try It Yourself


Test a missing port and a string-valued port and improve each error message.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Assuming a field is present because an example configuration happened to include it.
  • Printing complete configuration dictionaries that may contain API tokens or credentials.

Key Takeaways


  • Validate configuration before using it to control an application.
  • Configuration validation should reject missing required fields, incorrect data types and values outside permitted ranges.
  • TOML validates document syntax, not whether the resulting settings are meaningful for your program.
Share this resourceSend this page to someone who may find it useful.