Skip to content

Instantly share code, notes, and snippets.

@seansummers
Last active August 17, 2021 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seansummers/9f677e47a6f089da5b1598ce8d9c551c to your computer and use it in GitHub Desktop.
Save seansummers/9f677e47a6f089da5b1598ce8d9c551c to your computer and use it in GitHub Desktop.
Walk a Visitor to Leaves on a Graph in Python
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