Recipe 6.2 · Python
The Options Pattern with Validation
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
Typed settings help, but nothing checks them. A missing API key or a timeout of zero is only discovered when the first request that needs it fails, possibly hours after a deployment that everyone thought went fine.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Payment client reading unvalidated configuration values in its constructor
Source: ImproveCode, Chapter 6, Recipe 6.2 "The Options Pattern with Validation"
Section: The way it's often written
Book page: 125 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
A flat dict with "Section:Key" keys stands in for IConfiguration's indexer.
"""
from __future__ import annotations
from datetime import timedelta
class PaymentClient:
# Not this: no validation, failure appears at first use.
def __init__(self, config: dict[str, str]) -> None:
self._base_url = config.get("PaymentApi:BaseUrl") # None if misspelled
self._api_key = config.get("PaymentApi:ApiKey")
self._timeout = timedelta(
seconds=int(config.get("PaymentApi:TimeoutSeconds") or "0"))
The improved recipe
Register the settings class with the options pattern, validate it with DataAnnotations plus a custom validator for rules that span properties, and validate on startup.
If ApiKey is missing, the app now refuses to start and logs:
Microsoft.Extensions.Options.OptionsValidationException:
DataAnnotation validation failed for 'PaymentApiOptions' members:
'ApiKey' with the error: 'The ApiKey field is required.'.
Requirements: Python 3.12+. Install: pip install pydantic pydantic-settings
"""Strongly typed payment API options validated at startup
Source: ImproveCode, Chapter 6, Recipe 6.2 "The Options Pattern with Validation"
Section: The improved recipe
Book page: 125-126 -- original C# listing
Converted from C# to Python.
pydantic-settings replaces the options pattern: Field constraints and HttpUrl replace
the DataAnnotations, a model_validator replaces IValidateOptions, and constructing
the settings once at startup (load_payment_api_options) gives ValidateOnStart behavior.
Environment variables use the PAYMENTAPI__ prefix (PaymentApi:BaseUrl -> PAYMENTAPI__BASE_URL).
"""
from __future__ import annotations
from datetime import timedelta
from functools import lru_cache
from typing import ClassVar, Self
from pydantic import Field, HttpUrl, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
class PaymentApiOptions(BaseSettings):
model_config = SettingsConfigDict(env_prefix="PAYMENTAPI__")
SECTION_NAME: ClassVar[str] = "PaymentApi"
base_url: HttpUrl # [Required, Url]
api_key: str = Field(min_length=20) # [Required, MinLength(20)]
timeout_seconds: int = Field(default=30, ge=1, le=120)
max_retries: int = Field(default=3, ge=0, le=10)
@model_validator(mode="after")
def _validate(self) -> Self:
if not str(self.base_url).lower().startswith("https://"):
raise ValueError(f"{self.SECTION_NAME}:BaseUrl must use HTTPS.")
# Retries must fit inside a two-minute overall budget.
if self.timeout_seconds * (self.max_retries + 1) > 120:
raise ValueError(
"TimeoutSeconds x (MaxRetries + 1) must not exceed 120.")
return self
@lru_cache
def load_payment_api_options() -> PaymentApiOptions:
"""Call during startup so invalid settings stop the app immediately."""
return PaymentApiOptions() # type: ignore[call-arg]
class PaymentClient:
def __init__(self, options: PaymentApiOptions) -> None:
self._options = options
@property
def timeout(self) -> timedelta:
return timedelta(seconds=self._options.timeout_seconds)
@property
def base_address(self) -> str:
return str(self._options.base_url)
How it works
AddOptions<T>().BindConfiguration(section) tells the container how to build a
PaymentApiOptions from configuration. ValidateDataAnnotations runs the attributes, and every
registered IValidateOptions<T> runs after binding as well, so cross-property rules live in a
plain class you can unit test.
ValidateOnStart is the line that matters most. Without it, validation runs the first time
someone asks for options.Value, which might be the first payment of the day. With it, the host
validates every registered options class while starting and fails the deployment immediately,
with a message that names the section and the property. A failed deployment that says
"PaymentApi:ApiKey is required" takes a minute to fix. A payment outage at 9 A.M. doesn't.
The consumer asks for IOptions<PaymentApiOptions> and reads .Value once. It never sees
IConfiguration, and a test can pass Options.Create(new PaymentApiOptions { ... }).
There are three ways to consume options, and the choice matters:
| Interface | Lifetime | Picks up changes |
|---|---|---|
IOptions<T> |
Singleton | No, read once |
IOptionsSnapshot<T> |
Scoped | Per request |
IOptionsMonitor<T> |
Singleton | Yes, with OnChange |
Use IOptions<T> by default. Use IOptionsMonitor<T> in singletons that must react when a file
or Key Vault value changes, such as a feature flag.
Variations and pitfalls
[Required]on astringwith astring.Emptydefault still fails for an empty value, which is what you want. On anint,[Required]does nothing; use[Range].ValidateDataAnnotationschecks the top-level object only. For nested settings objects, either validate them in the custom validator or use the source-generated validator below with[ValidateObjectMembers]on the nested property.- .NET 8 adds a source-generated validator: a
partial classmarked[OptionsValidator]that implementsIValidateOptions<T>with no reflection. It's useful for trimmed or AOT apps. - Don't inject
IOptionsSnapshot<T>into a singleton. The container rejects it in Development with scope validation, and in Production you get a captured, stale value. - Validation messages go to the log. Never include the value of a secret in a failure message.