CKTIS / Python
collections.ChainMap
Searches layered mappings from first to last, using the first available binding.
Version: Python 3.14; repository image, production runtime not attested
Syntax
collections.ChainMap(*maps)Searches layered mappings from first to last, using the first available binding.
Direct writes target the first mapping even when a key already exists in a lower layer.
Use the first mapping for local settings and a later mapping for defaults. ChainMap holds references, so edits to either mapping affect subsequent reads. Deletion also targets the first mapping and raises KeyError for a key found only in defaults. In the example rate comes from override and assigning mode leaves base at 'a'.
from collections import ChainMap
defaults = {"timeout": 30}
config = ChainMap({}, defaults)
defaults["timeout"] = 60
assert config["timeout"] == 60
try:
del config["timeout"]
except KeyError:
assert defaults == {"timeout": 60}
else:
raise AssertionError
Examples
import collections
base = {"rate": 2, "mode": "a"}
override = {"rate": 5}
config = collections.ChainMap(override, base)
config["mode"] = "b"
print(config["rate"], config["mode"])
print(base["mode"], override["mode"])
Result
5 b a b
Use the first mapping for local settings and a later mapping for defaults. ChainMap holds references, so edits to either mapping affect subsequent reads. Deletion also targets the first mapping and raises KeyError for a key found only in defaults. In the example rate comes from override and assigning mode leaves base at 'a'.