Layered configuration
Layer command-line or request-specific settings over application defaults without copying the dictionaries.
Python · Class
ChainMap creates one dictionary-like view over multiple mappings. Lookups use the first matching mapping, while mutations target only the first mapping.
ChainMap presents several mappings as one dictionary-like view. Lookups inspect them from first to last, so earlier mappings take precedence; mutations affect only the first mapping, while all mappings remain linked by reference.
class collections.ChainMap(*maps)| Name | Type | Description |
|---|---|---|
*maps | mapping | Mappings to combine, searched from first to last; if omitted, an empty mapping is used. |
A ChainMap object providing a single view over the supplied mappings.
from collections import ChainMap
base = {"timeout": 30, "retries": 2}
overrides = {"timeout": 10}
config = ChainMap(overrides, base)
print(config["timeout"])
print(config["retries"])
config["retries"] = 3
print(base["retries"])
The override mapping wins for lookups, while assignment changes only that first mapping.
Layer command-line or request-specific settings over application defaults without copying the dictionaries.
Represent local variables followed by enclosing variables in a nested-scope model.
Provide template values with progressively broader fallback mappings.
ChainMap combines multiple mappings into one view without merging them into a new dictionary. A lookup checks mappings in order and returns the first matching key; changes are applied only to the first mapping.
Follow-up: How would you model a nested scope? Place the innermost scope first and outer scopes afterward, then use new_child() or parents to enter or leave levels.
When constructed without mappings, ChainMap supplies one empty dictionary, ensuring the chain always has an underlying mapping. Its mappings are held in the public maps list.
Follow-up: What risk follows from exposing maps? Code can reorder or replace the underlying mappings, changing lookup precedence and mutation targets.
ChainMap is useful when several mappings should remain separate but be viewed together, such as layered configuration or nested scopes. It can avoid repeatedly building a merged dictionary with update calls.
Follow-up: When should a copied dictionary be preferred? Use one when an independent snapshot is required rather than a live, reference-based view.
collections.ChainMap.mapscollections.ChainMap.new_child()collections.ChainMap.parentscollections.ChainMap.keys()collections.ChainMap.values()collections.ChainMap.items()