or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

import-export.mdindex.mdnode-construction.mdpath-resolution.mdsearch.mdtree-iteration.mdtree-rendering.mdutilities.md
tile.json

tessl/pypi-anytree

Powerful and Lightweight Python Tree Data Structure with various plugins

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/anytree@2.13.x

To install, run

npx @tessl/cli install tessl/pypi-anytree@2.13.0

index.mddocs/

Anytree

Powerful and Lightweight Python Tree Data Structure with various plugins. Anytree provides a comprehensive tree node implementation that can be used to build hierarchical data structures with parent-child relationships, extensive traversal capabilities, ASCII rendering, search functionality, and data export/import options.

Package Information

  • Package Name: anytree
  • Language: Python
  • Installation: pip install anytree
  • Version: 2.13.0
  • Requirements: Python >=3.9.2

Core Imports

from anytree import Node, AnyNode, RenderTree

Common specialized imports:

from anytree import (
    NodeMixin, LightNodeMixin,
    PreOrderIter, PostOrderIter, LevelOrderIter,
    find, findall, find_by_attr, findall_by_attr,
    Resolver, Walker
)

Import tree rendering styles:

from anytree import AsciiStyle, ContStyle, ContRoundStyle, DoubleStyle

Import export/import utilities:

from anytree.exporter import DictExporter, JsonExporter, DotExporter
from anytree.importer import DictImporter, JsonImporter

Basic Usage

from anytree import Node, RenderTree, AsciiStyle

# Create a simple tree structure
root = Node("Company")
engineering = Node("Engineering", parent=root)
marketing = Node("Marketing", parent=root)

# Add engineering teams
backend = Node("Backend", parent=engineering)
frontend = Node("Frontend", parent=engineering)
devops = Node("DevOps", parent=engineering)

# Add marketing teams
content = Node("Content", parent=marketing)
social = Node("Social Media", parent=marketing)

# Display the tree structure
print(RenderTree(root, style=AsciiStyle()))
# Output:
# Node('/Company')
# |-- Node('/Company/Engineering')
# |   |-- Node('/Company/Engineering/Backend')
# |   |-- Node('/Company/Engineering/Frontend')
# |   +-- Node('/Company/Engineering/DevOps')
# +-- Node('/Company/Marketing')
#     |-- Node('/Company/Marketing/Content')
#     +-- Node('/Company/Marketing/Social Media')

# Access tree properties
print(f"Root: {root}")
print(f"Engineering children: {engineering.children}")
print(f"Backend path: {backend.path}")
print(f"Tree depth from root: {root.height}")

Architecture

Anytree uses a flexible node-based architecture with several key components:

  • Node Classes: Core building blocks (Node, AnyNode, NodeMixin) providing parent-child relationships
  • Iterators: Multiple traversal strategies (PreOrder, PostOrder, LevelOrder, ZigZag)
  • Rendering: ASCII and Unicode tree visualization with customizable styles
  • Search: Flexible node finding with filtering and attribute-based searching
  • Resolution: Path-based node access with glob pattern support
  • Export/Import: Data exchange with dict, JSON, DOT (Graphviz), and Mermaid formats
  • Utilities: Helper functions for common tree operations

The design emphasizes flexibility - any Python class can be extended with tree functionality via NodeMixin, and all components work together seamlessly for building, traversing, searching, and visualizing hierarchical data structures.

Capabilities

Node Construction and Tree Building

Core node classes for building tree structures, including the base NodeMixin for extending any Python class with tree functionality, simple Node class with name identifier, and flexible AnyNode for arbitrary attributes.

class NodeMixin:
    def __init__(self): ...
    parent: Optional['NodeMixin']
    children: Tuple['NodeMixin', ...]
    ancestors: Tuple['NodeMixin', ...]
    descendants: Tuple['NodeMixin', ...]

class Node(NodeMixin):
    def __init__(self, name, parent=None, children=None, **kwargs): ...
    name: Any

class AnyNode(NodeMixin):
    def __init__(self, parent=None, children=None, **kwargs): ...

Node Construction

Tree Traversal and Iteration

Multiple iteration strategies for traversing tree structures including pre-order, post-order, level-order, and zigzag patterns, with filtering and depth control options.

class PreOrderIter:
    def __init__(self, node, filter_=None, stop=None, maxlevel=None): ...

class PostOrderIter:
    def __init__(self, node, filter_=None, stop=None, maxlevel=None): ...

class LevelOrderIter:
    def __init__(self, node, filter_=None, stop=None, maxlevel=None): ...

class LevelOrderGroupIter:
    def __init__(self, node, filter_=None, stop=None, maxlevel=None): ...

Tree Iteration

Tree Visualization and Rendering

ASCII and Unicode tree rendering with multiple built-in styles for displaying tree structures in console output and documentation.

class RenderTree:
    def __init__(self, node, style=ContStyle(), childiter=list, maxlevel=None): ...

class AsciiStyle:
    def __init__(self): ...

class ContStyle:
    def __init__(self): ...

class ContRoundStyle:
    def __init__(self): ...

Tree Rendering

Search and Filtering

Comprehensive search functionality for finding nodes by custom filters or attribute values, with support for depth limits and result count constraints.

def find(node, filter_=None, stop=None, maxlevel=None): ...
def find_by_attr(node, value, name="name", maxlevel=None): ...
def findall(node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None): ...
def findall_by_attr(node, value, name="name", maxlevel=None, mincount=None, maxcount=None): ...

Search Functions

Path Resolution and Navigation

Unix-style path resolution for accessing nodes by path strings, with support for absolute/relative paths, glob patterns, and navigation utilities.

class Resolver:
    def __init__(self, pathattr="name", ignorecase=False, relax=False): ...
    def get(self, node, path): ...
    def glob(self, node, path): ...

class Walker:
    @staticmethod
    def walk(start, end): ...

Path Resolution

Data Import and Export

Export tree structures to various formats (dict, JSON, DOT for Graphviz, Mermaid) and import from structured data formats for data exchange and visualization.

class DictExporter:
    def __init__(self, dictcls=dict, attriter=None, childiter=list, maxlevel=None): ...
    def export(self, node): ...

class JsonExporter:
    def __init__(self, dictcls=dict, attriter=None, childiter=list, maxlevel=None, **kwargs): ...
    def export(self, node): ...

class DotExporter:
    def __init__(self, node, graph="digraph", name="tree", options=None, ...): ...
    def export(self, node): ...

Import Export

Utility Functions

Helper functions for common tree operations including finding common ancestors, accessing sibling nodes, and performance-optimized cached search operations.

def commonancestors(*nodes): ...
def leftsibling(node): ...
def rightsibling(node): ...

Utilities

Exception Types

class TreeError(RuntimeError):
    """Base exception for tree-related errors."""

class LoopError(TreeError):
    """Exception raised when tree operations would create loops."""

class WalkError(RuntimeError):
    """Exception raised during tree walking operations."""

class CountError(RuntimeError):
    """Exception raised when search count constraints are violated."""

class ResolverError(RuntimeError):
    """Base exception for path resolution errors."""

class RootResolverError(ResolverError):
    """Exception when resolving from wrong root."""

class ChildResolverError(ResolverError):
    """Exception when child cannot be resolved."""