Recipe 6.1 · Python
From ConfigurationManager.AppSettings to IConfiguration
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
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
Settings are read as strings, deep inside business code, at the moment they are used. Missing or malformed values fail late and far from the cause. Classes can't be tested without a config file, and nobody can list which settings the application actually needs.
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.
"""Reading settings by string key with parsing and defaults scattered inline
Source: ImproveCode, Chapter 6, Recipe 6.1 "From ConfigurationManager.AppSettings to IConfiguration"
Section: The way it's often written
Book page: 122 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
os.environ stands in for ConfigurationManager.AppSettings.
"""
from __future__ import annotations
import os
# Not this: string keys, parsing and defaults scattered everywhere.
def run_import() -> None:
batch = int(os.environ["BatchSize"])
folder = os.environ.get("ImportFolder")
archive = os.environ.get("ArchiveFiles") == "true"
# ...
The improved recipe
Group related settings into a section in appsettings.json, bind the section to a class once at
the edge of the application, and pass the typed object to the code that needs it.
{
"Import": {
"Folder": "D:\\Data\\Inbound",
"BatchSize": 500,
"ArchiveFiles": true
}
}
Usage in a console tool:
Requirements: Python 3.12+. Install: pip install pydantic
"""Layered configuration builder bound to a typed settings class
Source: ImproveCode, Chapter 6, Recipe 6.1 "From ConfigurationManager.AppSettings to IConfiguration"
Section: The improved recipe
Book page: 122-123 -- original C# listing
Converted from C# to Python.
A small layered dict (appsettings.json, appsettings.{env}.json, environment variables
with "__" as the section separator, then --Section:Key=value command-line args) replaces
ConfigurationBuilder; pydantic binds the section to ImportSettings (like Get<T>()).
"""
from __future__ import annotations
import json
import os
import sys
from pathlib import Path
from typing import Any, ClassVar
from pydantic import BaseModel, ConfigDict
ConfigDictT = dict[str, Any]
class ImportSettings(BaseModel):
model_config = ConfigDict(populate_by_name=True)
SECTION_NAME: ClassVar[str] = "Import"
folder: str = ""
batch_size: int = 500
archive_files: bool = False
_FIELD_ALIASES = {"Folder": "folder", "BatchSize": "batch_size",
"ArchiveFiles": "archive_files"}
def _merge(target: ConfigDictT, path: list[str], value: Any) -> None:
for part in path[:-1]:
target = target.setdefault(part, {})
target[path[-1]] = value
def _deep_merge(target: ConfigDictT, source: ConfigDictT) -> None:
for key, value in source.items():
if isinstance(value, dict) and isinstance(target.get(key), dict):
_deep_merge(target[key], value)
else:
target[key] = value
class AppConfiguration:
@staticmethod
def build(args: list[str]) -> ConfigDictT:
"""Builds configuration for tools that don't use a framework.
Later sources override earlier ones."""
environment = os.environ.get("APP_ENVIRONMENT") or "Production"
base = Path(sys.argv[0]).resolve().parent
config: ConfigDictT = {}
with open(base / "appsettings.json", encoding="utf-8") as f: # optional: false
_deep_merge(config, json.load(f))
env_file = base / f"appsettings.{environment}.json"
if env_file.exists(): # optional: true
_deep_merge(config, json.loads(env_file.read_text(encoding="utf-8")))
for key, value in os.environ.items(): # environment variables
if "__" in key:
_merge(config, key.split("__"), value)
for arg in args: # command line
if arg.startswith("--") and "=" in arg:
key, value = arg[2:].split("=", 1)
_merge(config, key.split(":"), value)
return config
@staticmethod
def get_required_section[T: BaseModel](
configuration: ConfigDictT, section_name: str, model: type[T]
) -> T:
section = configuration.get(section_name)
if section is None:
raise RuntimeError(
f"Configuration section '{section_name}' is missing.")
data = {_FIELD_ALIASES.get(k, k): v for k, v in section.items()}
return model.model_validate(data)
class ImportJob:
def __init__(self, settings: ImportSettings) -> None:
self._settings = settings
def describe(self) -> str:
return (f"Importing from {self._settings.folder} in batches of "
f"{self._settings.batch_size}")
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Building configuration and creating the import job from a typed section
Source: ImproveCode, Chapter 6, Recipe 6.1 "From ConfigurationManager.AppSettings to IConfiguration"
Section: The improved recipe
Book page: 123 -- original C# listing
Converted from C# to Python.
AppConfiguration, ImportSettings and ImportJob are from
p122_r6_1_layered_config_typed_settings.py and are passed in.
"""
from __future__ import annotations
from typing import Any
def create_job(args: list[str], app_configuration: Any,
import_settings: Any, import_job: Any) -> Any:
config = app_configuration.build(args)
settings = app_configuration.get_required_section(
config, "Import", import_settings) # ImportSettings.SectionName
job = import_job(settings)
return job
How it works
ConfigurationBuilder merges several sources into one key-value view. The order matters: the
JSON file sets defaults, the environment-specific file overrides some of them, environment
variables override those, and command-line arguments win over everything. A key like
Import:BatchSize can come from any of them, and the code that reads it doesn't care which.
Get<T>() (from the binder, part of Microsoft.Extensions.Configuration.Binder) creates the
object and converts each value to the property type. "500" becomes an int, "true" becomes a
bool. Property defaults (BatchSize = 500) apply when a key is absent, so the default lives in
one obvious place instead of in every ?? "500" at every call site.
ImportJob takes ImportSettings in its constructor and never sees IConfiguration. That is the
real improvement. The job can be unit tested with new ImportSettings { BatchSize = 2 }, and the
list of settings it needs is visible in one class. Reading configuration only at the edge
(Program.cs, the composition root) keeps string keys out of business code.
In ASP.NET Core and the generic host, you don't need AppConfiguration.Build at all.
WebApplication.CreateBuilder and Host.CreateApplicationBuilder set up the same sources in the
same order, plus user secrets in Development. Recipe 6.2 shows how to register typed settings with
dependency injection.
Variations and pitfalls
- Keys are case-insensitive and nested with a colon (
Import:BatchSize). In environment variables, use a double underscore instead (Import__BatchSize), because colons aren't allowed in variable names on every platform. configuration.GetValue<int>("Import:BatchSize", 500)is fine for a one-off value in Program.cs. Don't scatter it through the code base; that isAppSettingswith a new name.- Binding fails quietly for misspelled keys: a property just keeps its default. Recipe 6.2 adds validation so a missing required value stops the app at startup.
- Mark JSON files
Copy if newer(the default forappsettings*.jsonin web projects, but not always in older console projects), or the file won't be next to the executable. - Arrays bind from JSON arrays or from indexed keys (
Import:Extensions:0), which is how you override one element from an environment variable.
On .NET Framework
Microsoft.Extensions.Configuration and its JSON, environment and binder packages target .NET
Standard 2.0, so they run on .NET Framework 4.6.1 and later. You can introduce appsettings.json
and typed settings classes into a 4.8 app today, building the configuration once in
Application_Start or Main. For keys that must stay in web.config, a small adapter that reads
ConfigurationManager.AppSettings once and fills a settings class gives you the same benefit.