ChainMap

Contents

ChainMap#

collections.ChainMap is a chain of dicts that the lookup falls through, leftmost first. Useful for layered config: CLI overrides win over environment variables, which win over defaults, without copying any of them.

from collections import ChainMap

defaults = {"timeout": 30, "retries": 3, "host": "localhost"}
env      = {"timeout": 15}
cli      = {"host": "example.com"}

cfg = ChainMap(cli, env, defaults)
cfg["timeout"]                # 15 (from env)
cfg["host"]                   # "example.com" (from cli)
cfg["retries"]                # 3 (from defaults)

Writes go to the leftmost map; the others are read-only through the chain.

cfg["timeout"] = 60           # mutates cli, not env or defaults

ChainMap is the right tool when the operator needs the override-with-layered-fallback semantic without the copy cost of {**defaults, **env, **cli}.

References#