Powerful and Lightweight Python Tree Data Structure with various plugins
npx @tessl/cli install tessl/pypi-anytree@2.13.0Powerful 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.
pip install anytreefrom anytree import Node, AnyNode, RenderTreeCommon 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, DoubleStyleImport export/import utilities:
from anytree.exporter import DictExporter, JsonExporter, DotExporter
from anytree.importer import DictImporter, JsonImporterfrom 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}")Anytree uses a flexible node-based architecture with several key components:
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.
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): ...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): ...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): ...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): ...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): ...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): ...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): ...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."""