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