Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 86f093f

Browse files
authored
bpo-36060: Document how collections.ChainMap() determines iteration order (GH-11969)
1 parent 7463884 commit 86f093f

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

Doc/library/collections.rst

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,21 @@ The class can be used to simulate nested scopes and is useful in templating.
100100
:func:`super` function. A reference to ``d.parents`` is equivalent to:
101101
``ChainMap(*d.maps[1:])``.
102102

103+
Note, the iteration order of a :class:`ChainMap()` is determined by
104+
scanning the mappings last to first::
105+
106+
>>> baseline = {'music': 'bach', 'art': 'rembrandt'}
107+
>>> adjustments = {'art': 'van gogh', 'opera': 'carmen'}
108+
>>> list(ChainMap(adjustments, baseline))
109+
['music', 'art', 'opera']
110+
111+
This gives the same ordering as a series of :meth:`dict.update` calls
112+
starting with the last mapping::
113+
114+
>>> combined = baseline.copy()
115+
>>> combined.update(adjustments)
116+
>>> list(combined)
117+
['music', 'art', 'opera']
103118

104119
.. seealso::
105120

Lib/test/test_collections.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,20 @@ def test_basics(self):
113113
self.assertEqual(f['b'], 5) # find first in chain
114114
self.assertEqual(f.parents['b'], 2) # look beyond maps[0]
115115

116+
def test_ordering(self):
117+
# Combined order matches a series of dict updates from last to first.
118+
# This test relies on the ordering of the underlying dicts.
119+
120+
baseline = {'music': 'bach', 'art': 'rembrandt'}
121+
adjustments = {'art': 'van gogh', 'opera': 'carmen'}
122+
123+
cm = ChainMap(adjustments, baseline)
124+
125+
combined = baseline.copy()
126+
combined.update(adjustments)
127+
128+
self.assertEqual(list(combined.items()), list(cm.items()))
129+
116130
def test_constructor(self):
117131
self.assertEqual(ChainMap().maps, [{}]) # no-args --> one new dict
118132
self.assertEqual(ChainMap({1:2}).maps, [{1:2}]) # 1 arg --> list

0 commit comments

Comments
 (0)