pythonpython-3.xtreeanytree

Generate ID for each node in a tree


I constructed a tree using anytree module in python. The code is as follows:

def list_anytree(lst):
    rootname = lst[0][0]
    node = Node(rootname)
    for j in lst:
        parentnode = node
        assert j[0] == parentnode.name
        for currentnodename in j[1:]:
            currentnode = next(
                (node for node in parentnode.children if node.name == currentnodename),
                None,
            )
            if currentnode is None:
                currentnode = Node((currentnodename), parent=parentnode)
            parentnode = currentnode
    return node

lst=[["a","b","c"],["a","b","d"],["a","b","c",]]

anytree=list_anytree(lst)
for pre,fill,node in RenderTree(anytree):
    print(f"{pre}{node.name}")

How can i assign a ID for each of the node in the tree?


Solution

  • The resulting tree is:

    a
    └── b
        ├── c
        └── d
    

    The node object instances are somehow already an id on its own. You can assign new attributes to objects at any time. For instance when you iterate over the tree

    for idx, node in enumerate(PreOrderIter(anytree)):
        node.idx = idx
    

    Or you make use of the python id() function, which gives a unique number. Please note that this number changes on every invocation:

    for pre, fill, node in RenderTree(anytree):
        id_ = id(node)
        print(f"{pre}{node.name} {node.idx} {id_:08X}")
    

    results in

    a 0 7FE95CDB1390
    └── b 1 7FE95CDB1FD0
        ├── c 2 7FE95CDC4048
        └── d 3 7FE95CDC4080