ChainMap Layers Config Precedence
Layer defaults, environment values, and CLI flags with collections.ChainMap: earlier mappings win, writes land in the first layer, and defaults stay intact.
Code
from collections import ChainMap
# 查找顺序即列表顺序:precedence 为 cli > env > defaults
defaults = {"host": "127.0.0.1", "port": 8080, "retries": 3}
env = {"port": 9090} # 环境变量层
cli = {"retries": 1, "dry_run": True} # 命令行参数层
settings = ChainMap(cli, env, defaults)
print(settings["host"], settings["port"], settings["retries"])
print("dry_run:", settings.get("dry_run", False))
# 新键写入最前层(cli),defaults 不被污染
settings["verbose"] = True
print("cli layer:", dict(settings.maps[0]))
print("defaults intact:", defaults)
# parents 视图去掉最前层:查看「环境层以下」的实际生效值
below = settings.parents
print("below cli:", below["port"], below["retries"])Output
Captured from a sandboxed run of this snippet in the build pipeline.
127.0.0.1 9090 1
dry_run: True
cli layer: {'retries': 1, 'dry_run': True, 'verbose': True}
defaults intact: {'host': '127.0.0.1', 'port': 8080, 'retries': 3}
below cli: 9090 3What to watch for
The constructor call fixes the precedence: ChainMap(cli, env, defaults) searches its maps left to right, so a CLI value outranks the same key in env, and defaults only supplies what neither layer above it defines. That is why settings["port"] prints 9090 — env wins — while settings["retries"] prints 1 from cli, and host falls through to the default 127.0.0.1.
Missing keys fall back the same way: settings.get("dry_run", False) finds True in the CLI layer instead of using the fallback. Writes always land in the front map — settings["verbose"] = True shows up in dict(settings.maps[0]) and leaves defaults untouched, as the two printed dictionaries confirm.
settings.parents returns a ChainMap without the first layer, which is how you inspect what would take effect below the CLI overrides: below["port"] is 9090 and below["retries"] is 3, the env-and-defaults view.
Interactive Tools for This Topic
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. Every import resolves inside the standard library — `collections`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.