bunch.py 784 B

1234567891011121314151617181920212223242526272829
  1. """Yet another implementation of bunch
  2. attribute-access of items on a dict.
  3. """
  4. # Copyright (c) Jupyter Development Team.
  5. # Distributed under the terms of the Modified BSD License.
  6. from __future__ import annotations
  7. from typing import Any
  8. class Bunch(dict): # type:ignore[type-arg]
  9. """A dict with attribute-access"""
  10. def __getattr__(self, key: str) -> Any:
  11. try:
  12. return self.__getitem__(key)
  13. except KeyError as e:
  14. raise AttributeError(key) from e
  15. def __setattr__(self, key: str, value: Any) -> None:
  16. self.__setitem__(key, value)
  17. def __dir__(self) -> list[str]:
  18. # py2-compat: can't use super because dict doesn't have __dir__
  19. names = dir({})
  20. names.extend(self.keys())
  21. return names