Last active
August 17, 2021 01:23
-
-
Save seansummers/9f677e47a6f089da5b1598ce8d9c551c to your computer and use it in GitHub Desktop.
Walk a Visitor to Leaves on a Graph in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections.abc import MutableMapping, MutableSequence | |
from typing import Callable, Iterable, Union | |
MutableCollection = Union[MutableMapping, MutableSequence] | |
Visitor = Callable[[str], str] # we only support string scalars for now | |
def visit(value: str) -> str: | |
"""Visit a string scalar, and mutate it if needed before returning it.""" | |
if len(value) > 4: # example criteria | |
return value[::-1] # example implementation | |
return value | |
def walk(graph: MutableCollection, visitor: Visitor) -> None: | |
"""Walk a updatable graph (nested collection supporting __getitem__ and __setitem__) | |
and visit the leaves in place. | |
""" | |
nodes: Iterable = tuple() | |
if isinstance(graph, MutableMapping): | |
nodes = graph.items() | |
elif isinstance(graph, MutableSequence): | |
nodes = enumerate(graph) | |
else: | |
raise ValueError( | |
f"I don't understand what {graph} is. It may not be updatable in place?" | |
) | |
for key, value in nodes: | |
if isinstance(value, str): | |
graph[key] = visitor(value) | |
else: | |
walk(value, visitor=visitor) | |
if __name__ == "__main__": | |
graph = { | |
"name": "sean", | |
"age": "too old", | |
"job": [{"description": "it's complicated"}], | |
"hobbies": ["linux", "food", "aws", "data structures"] | |
} | |
walk(graph, visitor) | |
print(graph) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment