or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

data-export.mdindex.mdtree-construction.mdtree-modification.mdtree-traversal.mdvisualization.md
tile.json

tessl/pypi-treelib

A Python implementation of tree data structure with hierarchical organization and efficient operations for traversal, modification, search, and visualization.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/treelib@1.8.x

To install, run

npx @tessl/cli install tessl/pypi-treelib@1.8.0

index.mddocs/

treelib

A comprehensive Python library for creating, manipulating, and visualizing hierarchical tree data structures. treelib provides an intuitive API with O(1) node access, multiple traversal algorithms, rich visualization options, and efficient operations for building tree-based applications.

Package Information

  • Package Name: treelib
  • Language: Python
  • Installation: pip install treelib

Core Imports

from treelib import Node, Tree

Basic Usage

from treelib import Tree

# Create a new tree
tree = Tree()

# Build tree structure
tree.create_node("Company", "company")
tree.create_node("Engineering", "eng", parent="company")
tree.create_node("Sales", "sales", parent="company")

# Add team members
tree.create_node("Alice", "alice", parent="eng")
tree.create_node("Bob", "bob", parent="eng")
tree.create_node("Carol", "carol", parent="sales")

# Display the tree
tree.show()

# Traverse all nodes
for node_id in tree.expand_tree():
    print(f"Visiting: {tree[node_id].tag}")

# Find specific nodes
eng_team = tree.children("eng")
all_employees = [tree[node].tag for node in tree.expand_tree() 
                if tree.level(node) > 1]

# Export to JSON
json_data = tree.to_json()

Architecture

treelib follows a dual-class architecture optimized for flexibility and performance:

  • Tree: Self-contained hierarchical structure managing nodes and relationships with O(1) lookup
  • Node: Elementary objects storing data and maintaining parent-child links across multiple tree contexts

Key design principles:

  • Each tree has exactly one root node (or none if empty)
  • Each non-root node has exactly one parent and zero or more children
  • Nodes can exist in multiple trees simultaneously with different relationships
  • All tree operations maintain structural integrity automatically

Capabilities

Tree Construction and Node Management

Create trees, add nodes, and build hierarchical structures with automatic relationship management and validation.

# Tree creation
def __init__(tree=None, deep=False, node_class=None, identifier=None): ...

# Node creation and addition
def create_node(tag=None, identifier=None, parent=None, data=None) -> Node: ...
def add_node(node, parent=None) -> None: ...

# Node access
def get_node(nid) -> Node | None: ...
def __getitem__(key) -> Node: ...
def __contains__(identifier) -> bool: ...

Tree Construction

Tree Traversal and Navigation

Navigate and traverse trees using multiple algorithms including depth-first, breadth-first, and zigzag patterns with filtering and sorting options.

# Tree traversal
def expand_tree(nid=None, mode=DEPTH, filter=None, key=None, reverse=False, sorting=True) -> Iterator[str]: ...
def rsearch(nid, filter=None) -> Iterator[str]: ...

# Structure queries
def children(nid) -> list[Node]: ...
def parent(nid) -> Node | None: ...
def siblings(nid) -> list[Node]: ...
def leaves(nid=None) -> list[Node]: ...

# Tree metrics
def size(level=None) -> int: ...
def depth(node=None) -> int: ...
def level(nid, filter=None) -> int: ...

Tree Traversal

Tree Modification Operations

Modify tree structure dynamically with move, remove, copy, and paste operations while maintaining data integrity.

# Tree modification
def move_node(source, destination) -> None: ...
def remove_node(identifier) -> int: ...
def update_node(nid, **attrs) -> None: ...

# Tree operations
def subtree(nid, identifier=None) -> Tree: ...
def remove_subtree(nid, identifier=None) -> Tree: ...
def paste(nid, new_tree, deep=False) -> None: ...
def merge(nid, new_tree, deep=False) -> None: ...

Tree Modification

Data Export and Import

Export trees to multiple formats including JSON, dictionaries, and GraphViz DOT for integration with other systems and visualization tools.

# Data export
def to_dict(nid=None, key=None, sort=True, reverse=False, with_data=False) -> dict: ...
def to_json(with_data=False, sort=True, reverse=False) -> str: ...
def to_graphviz(filename=None, shape="circle", graph="digraph", filter=None, key=None, reverse=False, sorting=True) -> None: ...

# Tree creation from data
@classmethod
def from_map(cls, child_parent_dict, id_func=None, data_func=None) -> Tree: ...

Data Export

Tree Visualization and Display

Rich tree visualization with customizable display formats, line styles, filtering, and file export capabilities.

# Tree display
def show(nid=None, level=ROOT, idhidden=True, filter=None, key=None, reverse=False, 
         line_type="ascii-ex", data_property=None, stdout=True, sorting=True) -> str | None: ...
def save2file(filename, nid=None, level=ROOT, idhidden=True, filter=None, key=None, 
              reverse=False, line_type="ascii-ex", data_property=None, sorting=True) -> None: ...

Visualization

Constants

Tree Traversal Modes

ROOT = 0     # Tree traversal starting from root level
DEPTH = 1    # Depth-first traversal mode
WIDTH = 2    # Breadth-first traversal mode  
ZIGZAG = 3   # Zigzag traversal mode

Node Update Modes

ADD = 0      # Add child to node
DELETE = 1   # Delete child from node
INSERT = 2   # Insert child (deprecated, use ADD)
REPLACE = 3  # Replace child with another

Node Class

class Node:
    def __init__(tag=None, identifier=None, expanded=True, data=None): ...
    
    # Class constants
    ADD = 0      # Add child to node
    DELETE = 1   # Delete child from node
    INSERT = 2   # Insert child (deprecated, use ADD)
    REPLACE = 3  # Replace child with another
    
    # Properties
    identifier: str       # Unique node identifier
    tag: str             # Human-readable display name
    expanded: bool       # Controls visibility in displays
    data: Any           # User-defined payload
    
    # Relationship query methods
    def predecessor(tree_id) -> str | None: ...
    def successors(tree_id) -> list[str]: ...
    def is_leaf(tree_id=None) -> bool: ...
    def is_root(tree_id=None) -> bool: ...
    
    # Relationship management methods
    def set_predecessor(nid, tree_id) -> None: ...
    def set_successors(value, tree_id=None) -> None: ...
    def update_successors(nid, mode=ADD, replace=None, tree_id=None) -> None: ...
    
    # Tree context management
    def clone_pointers(former_tree_id, new_tree_id) -> None: ...
    def reset_pointers(tree_id) -> None: ...
    def set_initial_tree_id(tree_id) -> None: ...
    
    # Special methods
    def __lt__(other) -> bool: ...  # Less-than comparison for sorting
    def __repr__() -> str: ...      # Detailed string representation

Exception Classes

class NodePropertyError(Exception): ...              # Base node attribute error
class NodeIDAbsentError(NodePropertyError): ...     # Node identifier doesn't exist
class NodePropertyAbsentError(NodePropertyError): ... # Node data property not specified
class MultipleRootError(Exception): ...             # Multiple root nodes detected
class DuplicatedNodeIdError(Exception): ...         # Duplicate node identifier
class LoopError(Exception): ...                     # Circular reference detected
class LinkPastRootNodeError(Exception): ...         # Invalid root node operation
class InvalidLevelNumber(Exception): ...            # Invalid level number specified

Common Use Cases

  • File system representations: Model directory structures and file hierarchies
  • Organizational charts: Represent company structures and reporting relationships
  • Decision trees: Build algorithmic decision-making structures
  • Category taxonomies: Create classification and tagging systems
  • Menu systems: Design hierarchical navigation interfaces
  • Family trees: Model genealogical relationships and lineage
  • Abstract syntax trees: Parse and represent code structures
  • Game trees: Model game states and move sequences