mirror of
https://github.com/python/cpython.git
synced 2025-10-01 21:02:15 +00:00
bpo-32792: Preserve mapping order in ChainMap() (GH-5586) (#GH-5617)
(cherry picked from commit 3793f95f98
)
Co-authored-by: Raymond Hettinger <rhettinger@users.noreply.github.com>
This commit is contained in:
parent
e603320975
commit
170b3f7950
3 changed files with 22 additions and 1 deletions
|
@ -914,7 +914,10 @@ class ChainMap(MutableMapping):
|
||||||
return len(set().union(*self.maps)) # reuses stored hash values if possible
|
return len(set().union(*self.maps)) # reuses stored hash values if possible
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
return iter(set().union(*self.maps))
|
d = {}
|
||||||
|
for mapping in reversed(self.maps):
|
||||||
|
d.update(mapping) # reuses stored hash values if possible
|
||||||
|
return iter(d)
|
||||||
|
|
||||||
def __contains__(self, key):
|
def __contains__(self, key):
|
||||||
return any(key in m for m in self.maps)
|
return any(key in m for m in self.maps)
|
||||||
|
|
|
@ -141,6 +141,23 @@ class TestChainMap(unittest.TestCase):
|
||||||
with self.assertRaises(KeyError):
|
with self.assertRaises(KeyError):
|
||||||
d.popitem()
|
d.popitem()
|
||||||
|
|
||||||
|
def test_order_preservation(self):
|
||||||
|
d = ChainMap(
|
||||||
|
OrderedDict(j=0, h=88888),
|
||||||
|
OrderedDict(),
|
||||||
|
OrderedDict(i=9999, d=4444, c=3333),
|
||||||
|
OrderedDict(f=666, b=222, g=777, c=333, h=888),
|
||||||
|
OrderedDict(),
|
||||||
|
OrderedDict(e=55, b=22),
|
||||||
|
OrderedDict(a=1, b=2, c=3, d=4, e=5),
|
||||||
|
OrderedDict(),
|
||||||
|
)
|
||||||
|
self.assertEqual(''.join(d), 'abcdefghij')
|
||||||
|
self.assertEqual(list(d.items()),
|
||||||
|
[('a', 1), ('b', 222), ('c', 3333), ('d', 4444),
|
||||||
|
('e', 55), ('f', 666), ('g', 777), ('h', 88888),
|
||||||
|
('i', 9999), ('j', 0)])
|
||||||
|
|
||||||
def test_dict_coercion(self):
|
def test_dict_coercion(self):
|
||||||
d = ChainMap(dict(a=1, b=2), dict(b=20, c=30))
|
d = ChainMap(dict(a=1, b=2), dict(b=20, c=30))
|
||||||
self.assertEqual(dict(d), dict(a=1, b=2, c=30))
|
self.assertEqual(dict(d), dict(a=1, b=2, c=30))
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
collections.ChainMap() preserves the order of the underlying mappings.
|
Loading…
Add table
Add a link
Reference in a new issue