Clarifying configuration script requirements
The user is asking for a Python script to parse and validate configuration files, which leaves a lot open to interpretation. I need clarification on the config format they want, like INI, YAML, JSON, or TOML, and what specific validation rules are necessary. I think I should design a flexible script that uses basic functionality and propose a generic config validator, making sure to accommodate both minimal solutions and optional enhancements.Proposing a common configuration validator
I’d like to ask the user for clarification but also think it’s good to propose a common solution, perhaps using YAML with libraries like Pydantic or JSONSchema. Since they might not be very chatty, I’ll suggest a concrete approach while mentioning it's adaptable. My goal is to create a configurable validator script called config_validator.py, which accepts paths for both the config and schema. I think I can keep the example simple by using JSON for format since it avoids external libraries.Designing the configuration parser
I’m considering using pydantic or dataclasses for validation, which would involve defining a config model, parsing a config file, and validating it while showing errors. However, since the user likely wants a straightforward code solution versus library recommendations, I’ll aim for a minimal script, ideally in YAML format since it's widely accepted – but that means I need to mention the requirement for PyYAML. I plan to provide a single script file along with an example config and a brief explanation. Ensuring clear error messages will be part of the design too!Defining the configuration schema
I need to focus on parsing the config file, ensuring that the top-level keys are app, logging, and database. Under app, the required keys are name (string) and optionally debug (boolean) and version (string). For logging, I’ll need level (with enum values of DEBUG/INFO/WARN/ERROR) and an optional file. The database section requires host, port, user, password, and an optional positive timeout. I’ll implement the YAML config and start building the config_validator.py script using argparse for the CLI.Creating the schema and validation logic
For clarity, I can define a simple nested dictionary schema for the configuration. The SCHEMA needs to specify required top-level keys like app, logging, and database, with various required and optional fields within them. I'll implement a validation function called validate, which ensures required keys are present, checks for unknown keys, and validates types.
I'll include code comments to guide the user, but I must be careful to keep things concise without excessive detail. The main function will handle loading the config file, and I'll ensure I provide an example schema in the final output along with relevant implementation details. Below is a self‑contained example of a Python script that:
- Parses a YAML configuration file
- Validates it against a simple schema (required keys, types, allowed values, numeric ranges)
- Reports any validation errors and exits with a non‑zero status if invalid
You can adapt the schema and/or switch to JSON/INI/TOML as needed.
1. Example configuration file (config.yaml)
app:
name: "MyApp"
debug: false
version: "1.0.0"
logging:
level: "INFO" # allowed: DEBUG, INFO, WARNING, ERROR, CRITICAL
file: "/var/log/myapp.log"
database:
host: "localhost"
port: 5432
user: "appuser"
password: "secret"
timeout: 10 # seconds, must be >= 1
2. Validation script (config_validator.py)
#!/usr/bin/env python3
"""
Validate a YAML configuration file against a simple schema.
Usage:
python config_validator.py path/to/config.yaml
"""
import argparse
import sys
from typing import Any, Dict, List, Tuple
try:
import yaml # pip install pyyaml
except ImportError: # pragma: no cover
print("This script requires PyYAML. Install it with: pip install pyyaml", file=sys.stderr)
sys.exit(1)
# ---------------------------------------------------------------------------
# Schema definition
# ---------------------------------------------------------------------------
# Simple schema format:
# {
# "key": {
# "type": <python_type>,
# "required": <bool>,
# "default": <any> (optional),
# "allowed": [list of allowed values] (optional),
# "min": <number> (optional),
# "max": <number> (optional),
# "schema": <nested schema for dict> (optional),
# "item_type": <python_type for list items> (optional),
# },
# ...
# }
SCHEMA: Dict[str, Any] = {
"app": {
"type": dict,
"required": True,
"schema": {
"name": {"type": str, "required": True},
"debug": {"type": bool, "required": False, "default": False},
"version": {"type": str, "required": False},
},
},
"logging": {
"type": dict,
"required": True,
"schema": {
"level": {
"type": str,
"required": True,
"allowed": ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
},
"file": {"type": str, "required": False},
},
},
"database": {
"type": dict,
"required": True,
"schema": {
"host": {"type": str, "required": True},
"port": {"type": int, "required": True, "min": 1, "max": 65535},
"user": {"type": str, "required": True},
"password": {"type": str, "required": True},
"timeout": {"type": int, "required": False, "default": 5, "min": 1},
},
},
}
# ---------------------------------------------------------------------------
# Validation logic
# ---------------------------------------------------------------------------
def validate_section(
data: Any,
schema: Dict[str, Any],
path: str = "",
) -> Tuple[Dict[str, Any], List[str]]:
"""
Validate a dictionary `data` against `schema`.
Returns (normalized_data, errors).
"""
errors: List[str] = []
result: Dict[str, Any] = {}
if not isinstance(data, dict):
errors.append(
f"{path or '<root>'}: expected a mapping/object, got {type(data).__name__}"
)
return result, errors
# Validate defined keys
for key, rules in schema.items():
full_key = f"{path}.{key}" if path else key
is_required = rules.get("required", False)
expected_type = rules.get("type")
if key not in data:
if is_required:
errors.append(f"Missing required key: {full_key}")
elif "default" in rules:
result[key] = rules["default"]
continue
value = data[key]
# Type check (special handling: bool is a subclass of int in Python)
if expected_type is not None:
if expected_type is bool:
if not isinstance(value, bool):
errors.append(
f"{full_key}: expected bool, got {type(value).__name__}"
)
continue
elif not isinstance(value, expected_type):
errors.append(
f"{full_key}: expected {expected_type.__name__}, got {type(value).__name__}"
)
continue
# Allowed values (enum)
if "allowed" in rules:
allowed = rules["allowed"]
if value not in allowed:
errors.append(
f"{full_key}: invalid value {value!r}, "
f"must be one of {allowed}"
)
continue
# Numeric range checks
if isinstance(value, (int, float)):
if "min" in rules and value < rules["min"]:
errors.append(
f"{full_key}: value {value} is less than minimum {rules['min']}"
)
if "max" in rules and value > rules["max"]:
errors.append(
f"{full_key}: value {value} is greater than maximum {rules['max']}"
)
# Nested dict
if expected_type is dict and "schema" in rules:
nested_result, nested_errors = validate_section(
value, rules["schema"], path=full_key
)
errors.extend(nested_errors)
result[key] = nested_result
continue
# List validation (optional; extend as needed)
if expected_type is list and "item_type" in rules:
item_type = rules["item_type"]
if not isinstance(value, list):
errors.append(f"{full_key}: expected list, got {type(value).__name__}")
continue
new_list = []
for idx, item in enumerate(value):
if not isinstance(item, item_type):
errors.append(
f"{full_key}[{idx}]: expected {item_type.__name__}, "
f"got {type(item).__name__}"
)
else:
new_list.append(item)
result[key] = new_list
continue
# If no special handling, accept value as-is
result[key] = value
# Unknown keys
allowed_keys = set(schema.keys())
for key in data.keys() - allowed_keys:
full_key = f"{path}.{key}" if path else key
errors.append(f"Unknown key: {full_key}")
return result, errors
def load_yaml(path: str) -> Any:
try:
with open(path, "r", encoding="utf-8") as f:
return yaml.safe_load(f) or {}
except FileNotFoundError:
print(f"Config file not found: {path}", file=sys.stderr)
sys.exit(1)
except yaml.YAMLError as e:
print(f"Failed to parse YAML: {e}", file=sys.stderr)
sys.exit(1)
def main() -> None:
parser = argparse.ArgumentParser(
description="Validate a YAML configuration file."
)
parser.add_argument(
"config_path",
help="Path to the YAML configuration file",
)
args = parser.parse_args()
raw_config = load_yaml(args.config_path)
if not isinstance(raw_config, dict):
print(
"Top-level configuration must be a mapping/object.",
file=sys.stderr,
)
sys.exit(1)
normalized_config, errors = validate_section(raw_config, SCHEMA)
if errors:
print("Configuration is INVALID:", file=sys.stderr)
for err in errors:
print(f" - {err}", file=sys.stderr)
sys.exit(1)
print("Configuration is valid.")
# Optional: print the normalized config (with defaults applied)
# import json
# print(json.dumps(normalized_config, indent=2))
if __name__ == "__main__":
main()
3. How to run
- Install dependency:
pip install pyyaml
- Save the files:
config.yaml as your configuration
config_validator.py as the script
- Run:
python config_validator.py config.yaml
- On success: prints
Configuration is valid. and exits with code 0.
- On failure: prints all validation errors and exits with code
1.
If you tell me which format you actually use (JSON, INI, TOML, custom syntax) and what kinds of rules you need (required keys, types, cross-field checks, etc.), I can tailor the script and schema exactly to your case.