Basic ExampleΒΆ

Simple configuration loading example.

 1"""
 2Basic example of using Varlord.
 3
 4This example demonstrates the most common use case:
 5loading configuration from defaults, environment variables, and CLI arguments.
 6
 7Run with:
 8    python basic_example.py --api-key your_key
 9    python basic_example.py -cv  # Check variables
10    python basic_example.py --help  # Show help
11"""
12
13from dataclasses import dataclass, field
14from typing import Optional
15
16from varlord import Config, sources
17from varlord.model_validation import RequiredFieldError
18
19
20@dataclass(frozen=True)
21class AppConfig:
22    """Application configuration model."""
23
24    # Required field (no default value)
25    api_key: str = field(metadata={"description": "API key for authentication"})
26
27    # Optional fields (with default values)
28    host: str = field(default="127.0.0.1", metadata={"description": "Server host address"})
29    port: int = field(default=8000, metadata={"description": "Server port number"})
30    debug: bool = field(default=False, metadata={"description": "Enable debug mode"})
31    timeout: float = field(default=30.0, metadata={"description": "Request timeout in seconds"})
32    hello_message: Optional[str] = field(
33        default=None, metadata={"description": "Optional greeting message"}
34    )
35
36
37def main():
38    """Main function."""
39    # Create config with multiple sources
40    # Model defaults are automatically applied - no need for sources.Defaults
41    # Sources filter by model fields automatically - model is auto-injected by Config
42    cfg = Config(
43        model=AppConfig,
44        sources=[
45            sources.Env(),  # Environment variables (HOST, PORT, etc.) - model auto-injected
46            sources.CLI(),  # Command-line arguments (--host, --port, etc.) - model auto-injected
47        ],
48    )
49
50    # Handle CLI commands (--help, -cv, etc.)
51    cfg.handle_cli_commands()
52
53    # Load configuration
54    # Note: api_key is required and must be provided via environment variable or CLI argument
55    # Example: export API_KEY=your_key or python basic_example.py --api-key your_key
56    try:
57        app = cfg.load()
58    except RequiredFieldError as e:
59        # Show friendly error message with field descriptions
60        print(f"Error loading configuration:\n{e}")
61        print("\nTip: Provide required fields via:")
62        print("  - Environment variable: export API_KEY=your_key")
63        print("  - CLI argument: python basic_example.py --api-key your_key")
64        print("  - For help: python basic_example.py --help")
65        return
66    except Exception as e:
67        print(f"Unexpected error: {e}")
68        return
69
70    # Use configuration
71    print(f"Starting server on {app.host}:{app.port}")
72    print(f"Debug mode: {app.debug}")
73    print(f"Timeout: {app.timeout}s")
74    if app.hello_message:
75        print(f"Message: {app.hello_message}")
76
77
78if __name__ == "__main__":
79    main()