Anytree
Anytree is a powerful and lightweight Python library that provides a tree data structure with various plugins. It simplifies the creation, manipulation, and visualization of hierarchical data. The library is actively maintained with regular releases, approximately every few months, and is currently at version 2.13.0.
Warnings
- breaking Python 2.x support was removed in version 2.9.0. Users upgrading from versions prior to 2.9.0 must migrate to Python 3.x.
- breaking The `anchestors` attribute, which was a typo for `ancestors`, is deprecated and will be removed in version 3.0.0.
- gotcha Prior to version 2.12.0, unpickling a tree containing a `SymlinkNode` could lead to a `RecursionError` due to issues in `__getattr__` for `SymlinkNodeMixin`.
- gotcha To export trees as images (e.g., PNG, DOT) using exporters like `DotExporter`, you must install the `graphviz` Python package (`pip install graphviz`) and the underlying `Graphviz` system tool separately.
- gotcha The `LightNodeMixin` (introduced in 2.12.0) behaves similarly to `NodeMixin` but uses `__slots__` for potentially better memory efficiency. This means it has minor differences in object behavior, such as not allowing arbitrary new attributes to be added dynamically after initialization.
Install
-
pip install anytree
Imports
- Node
from anytree import Node
- AnyNode
from anytree import AnyNode
- NodeMixin
from anytree import NodeMixin
- RenderTree
from anytree import RenderTree
- DotExporter
from anytree.exporter import DotExporter
- LightNodeMixin
from anytree import LightNodeMixin
Quickstart
from anytree import Node, RenderTree
# Create nodes by specifying parent
udo = Node("Udo")
marc = Node("Marc", parent=udo)
lian = Node("Lian", parent=marc)
dan = Node("Dan", parent=udo)
jet = Node("Jet", parent=dan)
jan = Node("Jan", parent=dan)
joe = Node("Joe", parent=dan)
# Or create a complex tree structure directly using children keyword
root_complex = Node("root", children=[
Node("sub0", children=[
Node("sub0B", foo=4, bar=109),
Node("sub0A")
]),
Node("sub1", children=[
Node("sub1A"),
Node("sub1B", bar=8),
Node("sub1C", children=[
Node("sub1Ca")
])
])
])
# Render the tree
for pre, fill, node in RenderTree(root_complex):
print(f"{pre}{node.name}")