Basics#
Adding Nodes#
Nodes are usually created by adding a new data instance to a parent:
from nutree import Tree, Node
tree = Tree("Store")
n = tree.add("Records")
n.add("Let It Be")
n.add("Get Yer Ya-Ya's Out!")
n = tree.add("Books")
n.add("The Little Prince")
tree.print()
Tree<'Store'>
├── 'Records'
│ ├── 'Let It Be'
│ ╰── "Get Yer Ya-Ya's Out!"
╰── 'Books'
╰── 'The Little Prince'
See also
See Working with Objects for details on how to manage arbitrary objects instead of plain strings.
Iteration#
Iterators are available for the hole tree or by branch. Different traversal methods are supported:
for node in tree:
# Depth-first, pre-order by default
...
# Alternatively use `visit` with a callback:
def callback(node, memo):
if node.name == "secret":
# Prevent visiting the child nodes:
return SkipBranch
if node.data.foobar == 17:
raise StopTraversal("found it")
# `res` contains the value passed to the `StopTraversal` constructor
res = tree.visit(callback) # res == "found it"
See also
See Search and Navigate for details on traversal.