'Clear maps[0], leaving maps[1:] intact.'
self.maps[0].clear()
+ def __ior__(self, other):
+ self.maps[0] |= other
+ return self
+
+ def __or__(self, other):
+ if isinstance(other, _collections_abc.Mapping):
+ m = self.maps[0].copy()
+ m.update(other)
+ return self.__class__(m, *self.maps[1:])
+ return NotImplemented
+
+ def __ror__(self, other):
+ if isinstance(other, _collections_abc.Mapping):
+ m = dict(other)
+ for child in reversed(self.maps):
+ m.update(child)
+ return self.__class__(m)
+ return NotImplemented
+
################################################################################
### UserDict
for k, v in dict(a=1, B=20, C=30, z=100).items(): # check get
self.assertEqual(d.get(k, 100), v)
+ def test_union_operators(self):
+ cm1 = ChainMap(dict(a=1, b=2), dict(c=3, d=4))
+ cm2 = ChainMap(dict(a=10, e=5), dict(b=20, d=4))
+ cm3 = cm1.copy()
+ d = dict(a=10, c=30)
+ pairs = [('c', 3), ('p',0)]
+
+ tmp = cm1 | cm2 # testing between chainmaps
+ self.assertEqual(tmp.maps, [cm1.maps[0] | dict(cm2), *cm1.maps[1:]])
+ cm1 |= cm2
+ self.assertEqual(tmp, cm1)
+
+ tmp = cm2 | d # testing between chainmap and mapping
+ self.assertEqual(tmp.maps, [cm2.maps[0] | d, *cm2.maps[1:]])
+ self.assertEqual((d | cm2).maps, [d | dict(cm2)])
+ cm2 |= d
+ self.assertEqual(tmp, cm2)
+
+ # testing behavior between chainmap and iterable key-value pairs
+ with self.assertRaises(TypeError):
+ cm3 | pairs
+ cm3 |= pairs
+ self.assertEqual(cm3.maps, [cm3.maps[0] | dict(pairs), *cm3.maps[1:]])
+
+ # testing proper return types for ChainMap and it's subclasses
+ class Subclass(ChainMap):
+ pass
+
+ class SubclassRor(ChainMap):
+ def __ror__(self, other):
+ return super().__ror__(other)
+
+ tmp = ChainMap() | ChainMap()
+ self.assertIs(type(tmp), ChainMap)
+ self.assertIs(type(tmp.maps[0]), dict)
+ tmp = ChainMap() | Subclass()
+ self.assertIs(type(tmp), ChainMap)
+ self.assertIs(type(tmp.maps[0]), dict)
+ tmp = Subclass() | ChainMap()
+ self.assertIs(type(tmp), Subclass)
+ self.assertIs(type(tmp.maps[0]), dict)
+ tmp = ChainMap() | SubclassRor()
+ self.assertIs(type(tmp), SubclassRor)
+ self.assertIs(type(tmp.maps[0]), dict)
+
################################################################################
### Named Tuples