chainmap.py 1017 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. from typing import (
  2. ChainMap,
  3. MutableMapping,
  4. TypeVar,
  5. cast,
  6. )
  7. _KT = TypeVar("_KT")
  8. _VT = TypeVar("_VT")
  9. class DeepChainMap(ChainMap[_KT, _VT]):
  10. """
  11. Variant of ChainMap that allows direct updates to inner scopes.
  12. Only works when all passed mapping are mutable.
  13. """
  14. def __setitem__(self, key: _KT, value: _VT) -> None:
  15. for mapping in self.maps:
  16. mutable_mapping = cast(MutableMapping[_KT, _VT], mapping)
  17. if key in mutable_mapping:
  18. mutable_mapping[key] = value
  19. return
  20. cast(MutableMapping[_KT, _VT], self.maps[0])[key] = value
  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)