Nutree (Tree Data Structures)
Nutree is a Python library for tree data structures with an intuitive, yet powerful, API. It allows handling of arbitrary objects in a hierarchical structure, offering features like navigation, searching, filtering, serialization to JSON and DOT, diffing, and typed child nodes. The library is actively maintained with regular releases, currently at version 1.1.0.
Warnings
- gotcha The Python `nutree` library is distinct from the JavaScript `nut-tree/nut.js` project. Ensure you are consulting the correct documentation and examples for the Python package.
- gotcha Advanced features like graph visualization (DOT, Mermaid) require installing optional dependencies using `pip install "nutree[graph]"` or `pip install "nutree[all]"`.
- gotcha Nutree nodes can wrap arbitrary objects, and the library handles multiple references to the same object ('clones') distinctly within the tree. Node lookup can be done by name, object reference, or a generated `data_id`, which might differ from direct Python object identity comparisons if not handled carefully.
Install
-
pip install nutree -
pip install "nutree[graph]" -
pip install "nutree[all]"
Imports
- Tree
from nutree import Tree
- Node
from nutree import Node
Quickstart
from nutree import Tree
# Create a new tree
tree = Tree("Root")
# Add nodes in a chained fashion
chapter1 = tree.add("Chapter 1")
chapter1.add("Section 1.1")
chapter1.add("Section 1.2")
# Go up to the root and add another branch
chapter2 = tree.add("Chapter 2")
chapter2.add("Section 2.1").add("Subsection 2.1.1")
# Pretty print the tree
tree.print()
# Access a node by name
section_1_1 = tree["Section 1.1"]
assert section_1_1.name == "Section 1.1"
# Add an arbitrary object as data to a node
class Task:
def __init__(self, name, priority):
self.name = name
self.priority = priority
def __str__(self):
return f"Task({self.name}, P:{self.priority})"
task_node = chapter1.add(Task("Review Draft", 1))
assert isinstance(task_node.data, Task)