Python Glossary Русский

Python 3.3+collectionsterm

collections.ChainMap

chainmap

Joins several dictionaries into a single view. Lookup goes through them in order. maps is the list of dictionaries, new_child() adds a new child level, parents is everything but the first one.

Syntax

collections.ChainMap(*maps)
.new_child(m=None)
.parents

ChainMap stores references rather than copies, so a later change in an underlying dict is visible through the chain right away — unlike the snapshot you get from {**defaults, **overrides}. The trap is the asymmetry between reads and writes: lookups scan every mapping, but assignment, pop and del touch only the first one, so deleting a key that is visible on read but actually lives in defaults raises KeyError.

Examples

from collections import ChainMap
defaults = {'color': 'red', 'size': 10}
user = {'color': 'blue'}
chain = ChainMap(user, defaults)
print(chain['color'])  # → blue  (из user)
print(chain['size'])  # → 10  (из defaults)
print(chain.maps)  # → [{'color': 'blue'}, {'color': 'red', 'size': 10}]
child = chain.new_child({'size': 20})
print(child['size'])  # → 20

See also

Open in the full glossarydocs.python.orgReport an inaccuracy