A Python implementation of tree data structure with hierarchical organization and efficient operations for traversal, modification, search, and visualization.
Comprehensive functionality for creating trees, adding nodes, and managing hierarchical structures. This module provides the foundation for building tree-based data structures with automatic relationship management and validation.
Create new tree instances with optional copying, custom node classes, and unique identifiers.
def __init__(tree=None, deep=False, node_class=None, identifier=None):
"""
Initialize a new tree or copy an existing tree.
Parameters:
- tree: Tree object to copy from (optional)
- deep: bool, perform deep copy if True
- node_class: Custom Node class to use
- identifier: Unique identifier for this tree instance
"""Usage Examples:
from treelib import Tree
# Create empty tree
tree = Tree()
# Create tree with custom identifier
tree = Tree(identifier="my_tree")
# Shallow copy of existing tree
tree_copy = Tree(existing_tree)
# Deep copy with independent data
tree_deep = Tree(existing_tree, deep=True)Create and add nodes to the tree structure with flexible parameter options.
def create_node(tag=None, identifier=None, parent=None, data=None) -> Node:
"""
Create and add a new node to the tree.
Parameters:
- tag: str, human-readable label for the node
- identifier: str, unique ID (auto-generated if None)
- parent: str, parent node identifier
- data: Any, custom data payload
Returns:
Node object that was created and added
"""Usage Examples:
# Create root node
tree.create_node("Root", "root")
# Create child with auto-generated ID
node = tree.create_node("Child", parent="root")
# Create node with custom data
tree.create_node("User", "user1", parent="root",
data={"name": "Alice", "role": "admin"})
# Create with all parameters
tree.create_node(tag="Project", identifier="proj1",
parent="root", data={"budget": 50000})Add existing Node objects to the tree structure.
def add_node(node, parent=None) -> None:
"""
Add an existing Node object to the tree.
Parameters:
- node: Node object to add
- parent: str, parent node identifier (optional for root)
"""Usage Examples:
from treelib import Node, Tree
# Create standalone node
node = Node("Standalone", "node1", data={"type": "external"})
# Add to tree
tree.add_node(node, parent="root")
# Add as root (if tree is empty)
root_node = Node("Root", "root")
tree.add_node(root_node)Safely access and query nodes within the tree structure.
def get_node(nid) -> Node | None:
"""
Safely retrieve a node without raising exceptions.
Parameters:
- nid: str, node identifier
Returns:
Node object if found, None otherwise
"""
def __getitem__(key) -> Node:
"""
Get node by identifier using bracket notation.
Parameters:
- key: str, node identifier
Returns:
Node object
Raises:
NodeIDAbsentError if node doesn't exist
"""
def __contains__(identifier) -> bool:
"""
Check if node exists using 'in' operator.
Parameters:
- identifier: str, node identifier
Returns:
bool, True if node exists
"""
def contains(nid) -> bool:
"""
Check if node exists in tree.
Parameters:
- nid: str, node identifier
Returns:
bool, True if node exists
"""Usage Examples:
# Safe node access
node = tree.get_node("user1")
if node:
print(f"Found: {node.tag}")
# Direct access (may raise exception)
user_node = tree["user1"]
# Membership testing
if "user1" in tree:
print("User exists")
# Alternative membership test
exists = tree.contains("user1")Retrieve and iterate over collections of nodes.
def all_nodes() -> list[Node]:
"""
Get all nodes as a list.
Returns:
list[Node], all nodes in the tree
"""
def all_nodes_itr() -> Iterator[Node]:
"""
Get all nodes as an iterator for memory efficiency.
Returns:
Iterator[Node], iterator over all nodes
"""
def filter_nodes(func) -> Iterator[Node]:
"""
Filter nodes by custom function.
Parameters:
- func: callable, filtering function that takes Node and returns bool
Returns:
Iterator[Node], filtered nodes
"""Usage Examples:
# Get all nodes
all_nodes = tree.all_nodes()
print(f"Total nodes: {len(all_nodes)}")
# Memory-efficient iteration
for node in tree.all_nodes_itr():
if node.data and "admin" in node.data.get("role", ""):
print(f"Admin user: {node.tag}")
# Custom filtering
admin_nodes = tree.filter_nodes(
lambda n: n.data and n.data.get("role") == "admin"
)Create trees from various data sources.
@classmethod
def from_map(cls, child_parent_dict, id_func=None, data_func=None) -> Tree:
"""
Create tree from child-parent mapping dictionary.
Parameters:
- child_parent_dict: dict, mapping of child -> parent relationships
- id_func: callable, function to generate node identifiers
- data_func: callable, function to generate node data
Returns:
Tree object constructed from the mapping
"""Usage Examples:
# Create from relationship mapping
relationships = {
"alice": "engineering",
"bob": "engineering",
"carol": "sales",
"engineering": "company",
"sales": "company",
"company": None # Root node
}
tree = Tree.from_map(relationships)
# With custom ID and data functions
tree = Tree.from_map(
relationships,
id_func=lambda x: x.lower().replace(" ", "_"),
data_func=lambda x: {"name": x, "created": datetime.now()}
)Access fundamental tree properties and metadata.
@property
def root() -> str | None:
"""
Get the identifier of the root node.
Returns:
str, root node identifier, or None if tree is empty
"""
@property
def identifier() -> str | None:
"""
Get the unique identifier of this tree instance.
Returns:
str, tree identifier, or None if not set
"""
@property
def nodes() -> dict[str, Node]:
"""
Get the internal nodes dictionary.
Returns:
dict[str, Node], mapping of node IDs to Node objects
"""
def __len__() -> int:
"""
Get the total number of nodes in the tree.
Returns:
int, number of nodes
"""Usage Examples:
# Access tree properties
print(f"Root node: {tree.root}")
print(f"Tree ID: {tree.identifier}")
print(f"Total nodes: {len(tree)}")
# Direct access to nodes dictionary (use with caution)
node_dict = tree.nodes
print(f"Node IDs: {list(node_dict.keys())}")Common exceptions raised during tree construction and node management:
class DuplicatedNodeIdError(Exception):
"""Raised when trying to add a node with existing identifier"""
class MultipleRootError(Exception):
"""Raised when tree would have multiple root nodes"""
class NodeIDAbsentError(Exception):
"""Raised when referencing non-existent node identifier"""Usage Examples:
from treelib import Tree, DuplicatedNodeIdError, NodeIDAbsentError
try:
tree.create_node("Duplicate", "existing_id")
except DuplicatedNodeIdError:
print("Node ID already exists")
try:
node = tree["missing_node"]
except NodeIDAbsentError:
print("Node not found")Install with Tessl CLI
npx tessl i tessl/pypi-treelib