Search code examples
pythontreeanytree

Simple list of branch for a Node Python AnyTree


Given a simple tree in AnyTree, when I look at a node it tells me its path to the root, but I cannot find anything that will simply give me that path as a list of the node names, or as a string which I can simply turn into a list of the names.

Typical example

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())

Which renders up as the tree:

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

I just want the path from a leaf to the top or root. So some command that will do this:

>>> ShowMePath(e,f)         # a command like this
["e", "d", "b", "f"] 

I'd even be happy if I could just get a string version of the node name which I could .split() to get that string.

>>> e 
Node('/f/b/d/e')       < can I get this as a string to split it? 

All the iterator methods examples (eg PostOrderIter) seem to return parallel branches rather than just a simple path to the top. I've looked through the docs but don't see this simple give-me-the-path option. What am I missing? Isn't this something everyone needs?


Solution

  • Okay - a solution. Turns out there is a .path attribute which returns a tuple of the path of nodes to the top. Didn't see that digging through the docs initially.

    So I can get to my desired list in the example above with:

    pathList = list(e.path)  
    namesList = [n.name for n in pathList] 
    

    and I'm there.