ML Foundations
Why ChainMap writes only to its first mapping
Understand layered lookup precedence, assignment, and the live links between ChainMap and its source mappings.

Evidence and testing
Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.
Lookups search layers in order
`collections.ChainMap` presents multiple mappings as one lookup view. It checks the first mapping, then each later mapping until it finds the key. This makes it useful for layered settings where a command-line value should override an environment value, which should override a default. [1]
The view keeps references to the original mappings. If a lower-priority mapping changes, a lookup can reflect that change as long as a higher-priority mapping does not already define the same key. The example changes the environment timeout before adding a command-line override to show both behaviors. [1]
References: [1]
Assignments target only the first mapping
Reading through the chain can make assignment behavior surprising. `config['timeout'] = 5` writes to the first mapping in the chain, even when the current value came from the environment mapping. It does not search for the mapping that supplied the old value and edit that source in place. [1]
This makes the first mapping a natural place for temporary overrides. If the application should persist a setting to a particular source, update that original dictionary explicitly. The printed mappings show the new value in `command_line` and the old value still in `environment`. [1, 2]
Use ChainMap as a view, not a merged copy
A ChainMap does not copy all the values into a new dictionary. That distinction matters when configuration sources remain mutable: changes to a source mapping may appear in later lookups, while an assignment through the chain goes to its first mapping. [1]
If a detached snapshot is needed, explicitly materialize a dictionary from the chain and treat that result as a copy. For ongoing layered configuration, keep the ChainMap and its source mappings, and make the write destination explicit in the code that handles updates. [1, 3]
Executed with Python 3.12.14; stdout captured.
from collections import ChainMap
defaults = {"timeout": 30, "retries": 2}
environment = {"timeout": 10}
command_line = {"retries": 4}
config = ChainMap(command_line, environment, defaults)
print("initial timeout:", config["timeout"])
print("initial retries:", config["retries"])
environment["timeout"] = 12
print("timeout after environment update:", config["timeout"])
config["timeout"] = 5
print("command-line mapping:", command_line)
print("environment mapping:", environment)
print("effective timeout:", config["timeout"])
Recorded output
initial timeout: 10
initial retries: 4
timeout after environment update: 12
command-line mapping: {'retries': 4, 'timeout': 5}
environment mapping: {'timeout': 12}
effective timeout: 5