anytree icon indicating copy to clipboard operation
anytree copied to clipboard

How to add a child by parent ID?

Open edent opened this issue 5 years ago • 3 comments

head = Node(123, id=123)

Node(456, id=456, parent=head)

print(RenderTree(head))
Node('/123', id=123)
└── Node('/123/456', id=456)

How do I add a child to the Node with ID 456?

All the examples in the documentation assume the nodes have a unique variable.

edent avatar Aug 08 '20 11:08 edent

Documentation writes:

Node: a simple tree node with at least a name attribute and any number of additional attributes.

Node names don't need to be unique. The following example works for me:

...
Node(456, id=456, parent=Node)  # adding a child to the Node with ID 456.

print(RenderTree(head))

# it prints the following:
Node('/123', id=123)
└── Node('/123/456', id=456)
    └── Node('/123/456/456', id=456)

Documentation:

Parameters: name – A name or any other object this node can reference to as idendifier.

Keyword Arguments: parent – Reference to parent node.children – Iterable with child nodes. * – Any other given attribute is just stored as object attribute.

Your id here do nothing special, it is not unique, it is a simple object attribute. If you want it to be special you can extend the Node class or use NodeMixin. Write an id property with unique checking in the setter. Python @property decorator

Hope it helps :)

slevi123 avatar Aug 13 '20 08:08 slevi123

Just to follow-up on this question, suppose I have a pre-existing tree as shown below:

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

If I need to add another node (lets say "j") as a child to the Node "d" then what would I need to do now? I do not have access to any variable references except the root Node root= Node("f") and do not have any Id's for the nodes. Would this still be possible?

rsdelhi91 avatar Dec 29 '21 14:12 rsdelhi91

Hi, this is implemented over here.

You can do a add_path_to_tree("f/b/d/j") to add Node "j" as child of Node "d"

https://bigtree.readthedocs.io/en/latest/bigtree/tree/construct.html#bigtree.tree.construct.add_path_to_tree

kayjan avatar Nov 12 '22 16:11 kayjan