path.py 923 B

12345678910111213141516171819202122232425262728
  1. from typing import Any, List, NamedTuple, Optional, Union
  2. __all__ = ["Path"]
  3. class Path(NamedTuple):
  4. """A generic path of string or integer indices"""
  5. prev: Any # Optional['Path'] (python/mypy/issues/731)
  6. """path with the previous indices"""
  7. key: Union[str, int]
  8. """current index in the path (string or integer)"""
  9. typename: Optional[str]
  10. """name of the parent type to avoid path ambiguity"""
  11. def add_key(self, key: Union[str, int], typename: Optional[str] = None) -> "Path":
  12. """Return a new Path containing the given key."""
  13. return Path(self, key, typename)
  14. def as_list(self) -> List[Union[str, int]]:
  15. """Return a list of the path keys."""
  16. flattened: List[Union[str, int]] = []
  17. append = flattened.append
  18. curr: Path = self
  19. while curr:
  20. append(curr.key)
  21. curr = curr.prev
  22. return flattened[::-1]