chainmap.py 991 B

123456789101112131415161718192021222324252627282930313233
  1. from typing import ChainMap, MutableMapping, TypeVar, cast
  2. _KT = TypeVar("_KT")
  3. _VT = TypeVar("_VT")
  4. class DeepChainMap(ChainMap[_KT, _VT]):
  5. """Variant of ChainMap that allows direct updates to inner scopes.
  6. Only works when all passed mapping are mutable.
  7. """
  8. def __setitem__(self, key: _KT, value: _VT) -> None:
  9. for mapping in self.maps:
  10. mutable_mapping = cast(MutableMapping[_KT, _VT], mapping)
  11. if key in mutable_mapping:
  12. mutable_mapping[key] = value
  13. return
  14. cast(MutableMapping[_KT, _VT], self.maps[0])[key] = value
  15. def __delitem__(self, key: _KT) -> None:
  16. """
  17. Raises
  18. ------
  19. KeyError
  20. If `key` doesn't exist.
  21. """
  22. for mapping in self.maps:
  23. mutable_mapping = cast(MutableMapping[_KT, _VT], mapping)
  24. if key in mapping:
  25. del mutable_mapping[key]
  26. return
  27. raise KeyError(key)