Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1from typing import ChainMap, MutableMapping, TypeVar, cast 

2 

3_KT = TypeVar("_KT") 

4_VT = TypeVar("_VT") 

5 

6 

7class DeepChainMap(ChainMap[_KT, _VT]): 

8 """Variant of ChainMap that allows direct updates to inner scopes. 

9 

10 Only works when all passed mapping are mutable. 

11 """ 

12 

13 def __setitem__(self, key: _KT, value: _VT) -> None: 

14 for mapping in self.maps: 

15 mutable_mapping = cast(MutableMapping[_KT, _VT], mapping) 

16 if key in mutable_mapping: 

17 mutable_mapping[key] = value 

18 return 

19 cast(MutableMapping[_KT, _VT], self.maps[0])[key] = value 

20 

21 def __delitem__(self, key: _KT) -> None: 

22 """ 

23 Raises 

24 ------ 

25 KeyError 

26 If `key` doesn't exist. 

27 """ 

28 for mapping in self.maps: 

29 mutable_mapping = cast(MutableMapping[_KT, _VT], mapping) 

30 if key in mapping: 

31 del mutable_mapping[key] 

32 return 

33 raise KeyError(key)