examples.23_config_validation
Demonstrates validating a configuration dictionary using constrained value
types such as RangeValue and EnumValue.
This example shows:
- How to validate multiple fields in a configuration dictionary.
- How to enforce numeric ranges, enumerated string values, and boolean flags.
- How to aggregate and return validation results in a structured form.
Run directly:
python examples/23_config_validation.py
Expected output:
GOOD: (True, {'port': 8080, 'log_level': 'info', 'feature_x': True}) BAD : (False, {'port': "Value must be one of 'int', got 'str'", 'log_level': "Value must be one of ('debug', 'info', 'warn', 'error'), got verbose", 'feature_x': "Value must be one of 'bool', got 'str'"})
1"""Demonstrates validating a configuration dictionary using constrained value 2types such as :class:`RangeValue` and :class:`EnumValue`. 3 4This example shows: 5 * How to validate multiple fields in a configuration dictionary. 6 * How to enforce numeric ranges, enumerated string values, and boolean flags. 7 * How to aggregate and return validation results in a structured form. 8 9Run directly: 10 11 python examples/23_config_validation.py 12 13Expected output: 14 15 GOOD: (True, {'port': 8080, 'log_level': 'info', 'feature_x': True}) 16 BAD : (False, {'port': "Value must be one of 'int', got 'str'", 'log_level': 17 "Value must be one of ('debug', 'info', 'warn', 'error'), got verbose", 18 'feature_x': "Value must be one of 'bool', got 'str'"}) 19""" 20 21import sys 22import pathlib 23from enum import Enum 24from typing import Dict, Tuple, Any 25 26# --------------------------------------------------------------------------- 27# Make repo root importable when running this file directly 28# --------------------------------------------------------------------------- 29sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) 30 31from constrained_values import RangeValue, Status, EnumValue 32 33 34class LogLevel(Enum): 35 """A simple enumeration representing valid log levels.""" 36 DEBUG = "debug" 37 INFO = "info" 38 WARN = "warn" 39 ERROR = "error" 40 41 42def validate_config(cfg: Dict[str, Any]) -> Tuple[bool, Dict[str, Any]]: 43 """Validate a configuration dictionary. 44 45 Uses constrained value types to validate each configuration field: 46 47 * **port** — must be within `[1024, 65535]` 48 * **log_level** — must match a member of :class:`LogLevel` 49 * **feature_x** — must be a boolean (`True` or `False`) 50 51 Args: 52 cfg: The configuration dictionary to validate. 53 54 Returns: 55 Tuple[bool, Dict[str, Any]]: A tuple containing: 56 * `True` and the validated config dict if all checks pass. 57 * `False` and a dict of error messages if validation fails. 58 """ 59 errors = {} 60 61 port = RangeValue(cfg.get("port"), 1024, 65535) 62 if port.status != Status.OK: 63 errors["port"] = port.details 64 65 level = EnumValue(cfg.get("log_level"), LogLevel) 66 if level.status != Status.OK: 67 errors["log_level"] = level.details 68 69 feature = EnumValue(cfg.get("feature_x"), [True, False]) 70 if feature.status != Status.OK: 71 errors["feature_x"] = feature.details 72 73 if errors: 74 return False, errors 75 76 return True, { 77 "port": port.value, 78 "log_level": level.value, 79 "feature_x": feature.value, 80 } 81 82 83def main() -> None: 84 """Run the configuration validation demonstration. 85 86 Creates two configuration dictionaries — one valid, one invalid — and 87 validates them using :func:`validate_config`. 88 89 Prints: 90 * The validation result for a good configuration (True, normalized dict). 91 * The validation result for a bad configuration (False, errors). 92 """ 93 good = {"port": 8080, "log_level": "info", "feature_x": True} 94 bad = {"port": "8080", "log_level": "verbose", "feature_x": "yes"} 95 96 print("GOOD:", validate_config(good)) 97 print("BAD :", validate_config(bad)) 98 99 100if __name__ == "__main__": 101 main()
35class LogLevel(Enum): 36 """A simple enumeration representing valid log levels.""" 37 DEBUG = "debug" 38 INFO = "info" 39 WARN = "warn" 40 ERROR = "error"
A simple enumeration representing valid log levels.
Inherited Members
- enum.Enum
- name
- value
43def validate_config(cfg: Dict[str, Any]) -> Tuple[bool, Dict[str, Any]]: 44 """Validate a configuration dictionary. 45 46 Uses constrained value types to validate each configuration field: 47 48 * **port** — must be within `[1024, 65535]` 49 * **log_level** — must match a member of :class:`LogLevel` 50 * **feature_x** — must be a boolean (`True` or `False`) 51 52 Args: 53 cfg: The configuration dictionary to validate. 54 55 Returns: 56 Tuple[bool, Dict[str, Any]]: A tuple containing: 57 * `True` and the validated config dict if all checks pass. 58 * `False` and a dict of error messages if validation fails. 59 """ 60 errors = {} 61 62 port = RangeValue(cfg.get("port"), 1024, 65535) 63 if port.status != Status.OK: 64 errors["port"] = port.details 65 66 level = EnumValue(cfg.get("log_level"), LogLevel) 67 if level.status != Status.OK: 68 errors["log_level"] = level.details 69 70 feature = EnumValue(cfg.get("feature_x"), [True, False]) 71 if feature.status != Status.OK: 72 errors["feature_x"] = feature.details 73 74 if errors: 75 return False, errors 76 77 return True, { 78 "port": port.value, 79 "log_level": level.value, 80 "feature_x": feature.value, 81 }
Validate a configuration dictionary.
Uses constrained value types to validate each configuration field:
- port — must be within
[1024, 65535]- log_level — must match a member of
LogLevel- feature_x — must be a boolean (
TrueorFalse)
Arguments:
- cfg: The configuration dictionary to validate.
Returns:
Tuple[bool, Dict[str, Any]]: A tuple containing: *
Trueand the validated config dict if all checks pass. *Falseand a dict of error messages if validation fails.
84def main() -> None: 85 """Run the configuration validation demonstration. 86 87 Creates two configuration dictionaries — one valid, one invalid — and 88 validates them using :func:`validate_config`. 89 90 Prints: 91 * The validation result for a good configuration (True, normalized dict). 92 * The validation result for a bad configuration (False, errors). 93 """ 94 good = {"port": 8080, "log_level": "info", "feature_x": True} 95 bad = {"port": "8080", "log_level": "verbose", "feature_x": "yes"} 96 97 print("GOOD:", validate_config(good)) 98 print("BAD :", validate_config(bad))
Run the configuration validation demonstration.
Creates two configuration dictionaries — one valid, one invalid — and
validates them using validate_config().
Prints:
- The validation result for a good configuration (True, normalized dict).
- The validation result for a bad configuration (False, errors).