Python Snippet

ChainMap for Layered Configs

Difficulty: Medium

`collections.ChainMap` lets you stack multiple dicts and treat them as a single read-through view, with later dicts shadowing earlier ones. It is the right primitive for layered configs (defaults, environment, user overrides), nested scopes, and anywhere you would otherwise merge dicts repeatedly. This snippet covers the basic stacking, lookup-with-fallback semantics, and how new keys land in the first map by default.

Code Snippets
/

ChainMap for Layered Configs

ChainMap for Layered Configs

`collections.ChainMap` lets you stack multiple dicts and treat them as a single read-through view, with later dicts shadowing earlier ones. It is the right primitive for layered configs (defaults, environment, user overrides), nested scopes, and anywhere you would otherwise merge dicts repeatedly. This snippet covers the basic stacking, lookup-with-fallback semantics, and how new keys land in the first map by default.

Python
Medium
3 snippets
py-collections
py-standard-library
code-template
cheat-sheet

451 views

10

ChainMap looks up keys by walking its maps in order, returning the first match. So ChainMap(request, user, defaults) reads as 'request takes priority, then user, then defaults'. This is the cleanest expression of layered configuration in the Python standard library. Iterating the chain returns each unique key exactly once, in first-occurrence order. The chain holds references to the underlying dicts (no copy), so updating any layer is immediately visible through the view.