pythoniterationanytree

Python anytree: When iterating, know when branch is closed


Using example from documentation:

from anytree import Node, RenderTree, AsciiStyle

f = Node("f")
b = Node("b", parent=f)
a = Node("a", parent=b)
d = Node("d", parent=b)
c = Node("c", parent=d)
e = Node("e", parent=d)
g = Node("g", parent=f)
i = Node("i", parent=g)
h = Node("h", parent=i)
print(RenderTree(f, style=AsciiStyle()).by_attr())

f 
|-- b
|   |-- a
|   +-- d
|       |-- c
|       +-- e
+-- g
    +-- i
        +-- h

The tree in my case is an internal representation of a file format. At some point I want to write it to a file. The format commands that each node has an opening and a closing tag. (like in html or xml but it's binary format).

If a node is a leaf it's easy to realize it needs a close tag but not for higher level nodes. Using PreOrderIterI would need to output this:

open f -> f -> open b -> b -> open a -> a -> close a -> open d -> d -> open c -> c -> close c-> open e -> e-> close e -> close d -> close b

And so forth. Issue is how I can realize a nodes children have all been traversed and then write close tag?


Solution

  • No worries. You can still do something like

    def traverse(node):
        print("open " + node + " -> " + node + " -> ")
        for child in node.children:
             traverse(child)
        print("close " + node + " -> ")