Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bpo-36060: Document how collections.ChainMap() determines iteration order #11969

Merged
merged 4 commits into from
Feb 21, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Doc/library/collections.rst
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,21 @@ The class can be used to simulate nested scopes and is useful in templating.
:func:`super` function. A reference to ``d.parents`` is equivalent to:
``ChainMap(*d.maps[1:])``.

Note, the iteration order of a :class:`ChainMap()` is determined by
scanning the mappings last to first::

>>> baseline = {'music': 'bach', 'art': 'rembrandt'}
>>> adjustments = {'art': 'van gogh', 'opera': 'carmen'}
>>> list(ChainMap(adjustments, baseline))
['music', 'art', 'opera']

This gives the same ordering as a series of :meth:`dict.update` calls
starting with the last mapping::

>>> combined = baseline.copy()
>>> combined.update(adjustments)
>>> list(combined)
['music', 'art', 'opera']

.. seealso::

Expand Down
14 changes: 14 additions & 0 deletions Lib/test/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,20 @@ def test_basics(self):
self.assertEqual(f['b'], 5) # find first in chain
self.assertEqual(f.parents['b'], 2) # look beyond maps[0]

def test_ordering(self):
# Combined order matches a series of dict updates from last to first.
# This test relies on the ordering of the underlying dicts.

baseline = {'music': 'bach', 'art': 'rembrandt'}
adjustments = {'art': 'van gogh', 'opera': 'carmen'}

cm = ChainMap(adjustments, baseline)

combined = baseline.copy()
combined.update(adjustments)

self.assertEqual(list(combined.items()), list(cm.items()))

def test_constructor(self):
self.assertEqual(ChainMap().maps, [{}]) # no-args --> one new dict
self.assertEqual(ChainMap({1:2}).maps, [{1:2}]) # 1 arg --> list
Expand Down