0
# Anytree
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: anytree
7
- **Language**: Python
8
- **Installation**: `pip install anytree`
9
- **Version**: 2.13.0
10
- **Requirements**: Python >=3.9.2
11
12
## Core Imports
13
14
```python
15
from anytree import Node, AnyNode, RenderTree
16
```
17
18
Common specialized imports:
19
20
```python
21
from anytree import (
22
NodeMixin, LightNodeMixin,
23
PreOrderIter, PostOrderIter, LevelOrderIter,
24
find, findall, find_by_attr, findall_by_attr,
25
Resolver, Walker
26
)
27
```
28
29
Import tree rendering styles:
30
31
```python
32
from anytree import AsciiStyle, ContStyle, ContRoundStyle, DoubleStyle
33
```
34
35
Import export/import utilities:
36
37
```python
38
from anytree.exporter import DictExporter, JsonExporter, DotExporter
39
from anytree.importer import DictImporter, JsonImporter
40
```
41
42
## Basic Usage
43
44
```python
45
from anytree import Node, RenderTree, AsciiStyle
46
47
# Create a simple tree structure
48
root = Node("Company")
49
engineering = Node("Engineering", parent=root)
50
marketing = Node("Marketing", parent=root)
51
52
# Add engineering teams
53
backend = Node("Backend", parent=engineering)
54
frontend = Node("Frontend", parent=engineering)
55
devops = Node("DevOps", parent=engineering)
56
57
# Add marketing teams
58
content = Node("Content", parent=marketing)
59
social = Node("Social Media", parent=marketing)
60
61
# Display the tree structure
62
print(RenderTree(root, style=AsciiStyle()))
63
# Output:
64
# Node('/Company')
65
# |-- Node('/Company/Engineering')
66
# | |-- Node('/Company/Engineering/Backend')
67
# | |-- Node('/Company/Engineering/Frontend')
68
# | +-- Node('/Company/Engineering/DevOps')
69
# +-- Node('/Company/Marketing')
70
# |-- Node('/Company/Marketing/Content')
71
# +-- Node('/Company/Marketing/Social Media')
72
73
# Access tree properties
74
print(f"Root: {root}")
75
print(f"Engineering children: {engineering.children}")
76
print(f"Backend path: {backend.path}")
77
print(f"Tree depth from root: {root.height}")
78
```
79
80
## Architecture
81
82
Anytree uses a flexible node-based architecture with several key components:
83
84
- **Node Classes**: Core building blocks (Node, AnyNode, NodeMixin) providing parent-child relationships
85
- **Iterators**: Multiple traversal strategies (PreOrder, PostOrder, LevelOrder, ZigZag)
86
- **Rendering**: ASCII and Unicode tree visualization with customizable styles
87
- **Search**: Flexible node finding with filtering and attribute-based searching
88
- **Resolution**: Path-based node access with glob pattern support
89
- **Export/Import**: Data exchange with dict, JSON, DOT (Graphviz), and Mermaid formats
90
- **Utilities**: Helper functions for common tree operations
91
92
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.
93
94
## Capabilities
95
96
### Node Construction and Tree Building
97
98
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.
99
100
```python { .api }
101
class NodeMixin:
102
def __init__(self): ...
103
parent: Optional['NodeMixin']
104
children: Tuple['NodeMixin', ...]
105
ancestors: Tuple['NodeMixin', ...]
106
descendants: Tuple['NodeMixin', ...]
107
108
class Node(NodeMixin):
109
def __init__(self, name, parent=None, children=None, **kwargs): ...
110
name: Any
111
112
class AnyNode(NodeMixin):
113
def __init__(self, parent=None, children=None, **kwargs): ...
114
```
115
116
[Node Construction](./node-construction.md)
117
118
### Tree Traversal and Iteration
119
120
Multiple iteration strategies for traversing tree structures including pre-order, post-order, level-order, and zigzag patterns, with filtering and depth control options.
121
122
```python { .api }
123
class PreOrderIter:
124
def __init__(self, node, filter_=None, stop=None, maxlevel=None): ...
125
126
class PostOrderIter:
127
def __init__(self, node, filter_=None, stop=None, maxlevel=None): ...
128
129
class LevelOrderIter:
130
def __init__(self, node, filter_=None, stop=None, maxlevel=None): ...
131
132
class LevelOrderGroupIter:
133
def __init__(self, node, filter_=None, stop=None, maxlevel=None): ...
134
```
135
136
[Tree Iteration](./tree-iteration.md)
137
138
### Tree Visualization and Rendering
139
140
ASCII and Unicode tree rendering with multiple built-in styles for displaying tree structures in console output and documentation.
141
142
```python { .api }
143
class RenderTree:
144
def __init__(self, node, style=ContStyle(), childiter=list, maxlevel=None): ...
145
146
class AsciiStyle:
147
def __init__(self): ...
148
149
class ContStyle:
150
def __init__(self): ...
151
152
class ContRoundStyle:
153
def __init__(self): ...
154
```
155
156
[Tree Rendering](./tree-rendering.md)
157
158
### Search and Filtering
159
160
Comprehensive search functionality for finding nodes by custom filters or attribute values, with support for depth limits and result count constraints.
161
162
```python { .api }
163
def find(node, filter_=None, stop=None, maxlevel=None): ...
164
def find_by_attr(node, value, name="name", maxlevel=None): ...
165
def findall(node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None): ...
166
def findall_by_attr(node, value, name="name", maxlevel=None, mincount=None, maxcount=None): ...
167
```
168
169
[Search Functions](./search.md)
170
171
### Path Resolution and Navigation
172
173
Unix-style path resolution for accessing nodes by path strings, with support for absolute/relative paths, glob patterns, and navigation utilities.
174
175
```python { .api }
176
class Resolver:
177
def __init__(self, pathattr="name", ignorecase=False, relax=False): ...
178
def get(self, node, path): ...
179
def glob(self, node, path): ...
180
181
class Walker:
182
@staticmethod
183
def walk(start, end): ...
184
```
185
186
[Path Resolution](./path-resolution.md)
187
188
### Data Import and Export
189
190
Export tree structures to various formats (dict, JSON, DOT for Graphviz, Mermaid) and import from structured data formats for data exchange and visualization.
191
192
```python { .api }
193
class DictExporter:
194
def __init__(self, dictcls=dict, attriter=None, childiter=list, maxlevel=None): ...
195
def export(self, node): ...
196
197
class JsonExporter:
198
def __init__(self, dictcls=dict, attriter=None, childiter=list, maxlevel=None, **kwargs): ...
199
def export(self, node): ...
200
201
class DotExporter:
202
def __init__(self, node, graph="digraph", name="tree", options=None, ...): ...
203
def export(self, node): ...
204
```
205
206
[Import Export](./import-export.md)
207
208
### Utility Functions
209
210
Helper functions for common tree operations including finding common ancestors, accessing sibling nodes, and performance-optimized cached search operations.
211
212
```python { .api }
213
def commonancestors(*nodes): ...
214
def leftsibling(node): ...
215
def rightsibling(node): ...
216
```
217
218
[Utilities](./utilities.md)
219
220
## Exception Types
221
222
```python { .api }
223
class TreeError(RuntimeError):
224
"""Base exception for tree-related errors."""
225
226
class LoopError(TreeError):
227
"""Exception raised when tree operations would create loops."""
228
229
class WalkError(RuntimeError):
230
"""Exception raised during tree walking operations."""
231
232
class CountError(RuntimeError):
233
"""Exception raised when search count constraints are violated."""
234
235
class ResolverError(RuntimeError):
236
"""Base exception for path resolution errors."""
237
238
class RootResolverError(ResolverError):
239
"""Exception when resolving from wrong root."""
240
241
class ChildResolverError(ResolverError):
242
"""Exception when child cannot be resolved."""
243
```