Python ChainMap: keep overrides in the first mapping
An override layer should accept a local change without rewriting shared defaults. ChainMap can provide that view, but deleting an override can reveal a fallback value again.
Set up
Tested on Linux with CPython 3.12.14. Use Python 3.12 or later, Bash, a text editor, mktemp, rm and rmdir. The example needs no network access. Run the steps in the same terminal and stop if setup fails. Run Python without -O so the assertions stay enabled.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save this as chainmap_overrides.py:
from collections import ChainMap
local = {}
defaults = {"timeout": 30, "region": "west"}
settings = ChainMap(local, defaults)
print("fallback:", settings["timeout"])
settings["timeout"] = 5
print("local:", local)
print("defaults:", defaults)
del settings["timeout"]
print("after deleting override:", settings["timeout"])
try:
del settings["region"]
except KeyError:
print("cannot delete a fallback-only key")
defaults["region"] = "east"
print("updated fallback:", settings["region"])
assert local == {}
assert defaults == {"timeout": 30, "region": "east"}Run:
python3 -B chainmap_overrides.pyObserved output:
fallback: 30
local: {'timeout': 5}
defaults: {'timeout': 30, 'region': 'west'}
after deleting override: 30
cannot delete a fallback-only key
updated fallback: eastChoose the writable layer explicitly
The ChainMap documentation specifies first-mapping writes and deletions. A lookup searches mappings in order, so the initial timeout comes from defaults. Assignment puts timeout in local; deleting that entry exposes the original timeout.
Deleting region fails even though reading it succeeds. A deletion does not search later mappings. If an application needs to hide an inherited setting, define a separate masking convention and make every consumer honor it. Removing a local entry alone will not do that.
Limits
The view holds references to the dictionaries. Changing defaults later changes fallback reads through settings. Use dict(settings) when you need a shallow snapshot of the resolved values; nested mutable values remain shared. Keep the first mapping writable, and avoid assuming that this view provides synchronization for concurrent writers.
Clean up
Remove the example file and the temporary directory:
rm -- chainmap_overrides.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.