@dataclass class Node: id: str children: List[Node] = field(default_factory=list) # beautiful Python: traverse a tree depth-first, pre-order (stack based) def __iter__(self): stack = [self] while stack: node = stack.pop() yield node stack = node.children + stack