API Reference¶
This is the complete API reference for AlgoTree v1.0+.
Core Classes¶
Node¶
- class AlgoTree.Node(name: str, *children: Node, attrs: Dict[str, Any] | None = None, parent: Node | None = None)[source]¶
Bases:
objectImmutable tree node with functional operations.
All operations return new trees, preserving immutability. Uses structural sharing for efficiency.
- property attrs: Dict[str, Any]¶
Node attributes (returns copy to prevent mutation).
- property depth: int¶
Get depth from root (root has depth 0).
- filter(predicate: Callable[[Node], bool]) Node | None[source]¶
Filter tree to nodes matching predicate.
Returns None if this node doesn’t match and has no matching descendants. Preserves structure for matching nodes and their ancestors.
- filter_children(predicate: Callable[[Node], bool]) Node[source]¶
Return new node with only children matching predicate.
- find(selector: str | Callable[[Node], bool] | Selector) Node | None[source]¶
Find first node matching selector.
- find_all(selector: str | Callable[[Node], bool] | Selector) List[Node][source]¶
Find all nodes matching selector.
- static from_dict(data: Dict[str, Any]) Node[source]¶
Create node tree from nested dictionary.
- Parameters:
data – Dictionary with ‘name’, optional attributes, and optional ‘children’ list
- Returns:
Root node of reconstructed tree
- property height: int¶
Get height of subtree rooted at this node.
- property is_leaf: bool¶
Check if this is leaf node.
- property is_root: bool¶
Check if this is root node.
- map_children(fn: Callable[[Node], Node]) Node[source]¶
Return new node with function applied to all children.
- property name: str¶
Node name (immutable).
- property path: str¶
Get path from root as string.
- property size: int¶
Get total number of nodes in subtree.
- to_dict() Dict[str, Any][source]¶
Convert tree to nested dictionary.
- Returns:
Dictionary with ‘name’, attributes, and ‘children’ list
from AlgoTree import Node
# Create nodes
root = Node("root", type="container")
child = root.add_child("child", value=42)
# Access properties
print(root.name) # "root"
print(root.payload) # {"type": "container"}
print(root.children) # [child]
print(root.is_root) # True
print(child.parent) # root
print(child.level) # 1
TreeBuilder¶
- class AlgoTree.TreeBuilder(name: str, **attrs)[source]¶
Bases:
objectFluent builder for constructing trees.
Example
- tree = (
TreeBuilder(‘root’) .attr(type=’directory’) .child(‘src’,
TreeBuilder(‘main.py’, type=’file’, size=1024), TreeBuilder(‘utils.py’, type=’file’, size=512)
) .child(‘docs’,
TreeBuilder(‘README.md’, type=’file’)
) .build()
)
- attr(**attrs) TreeBuilder[source]¶
Add or update attributes.
- Parameters:
**attrs – Attributes to add/update
- Returns:
Self for chaining
- attrs(attrs: Dict[str, Any]) TreeBuilder[source]¶
Set attributes from dictionary.
- Parameters:
attrs – Dictionary of attributes
- Returns:
Self for chaining
- build_node() Node[source]¶
Build just the node (not wrapped in Tree).
- Returns:
Constructed Node object
- child(name_or_builder: str | TreeBuilder | Node, *children: TreeBuilder | Node, **attrs) TreeBuilder[source]¶
Add child node(s).
- Parameters:
name_or_builder – Child name, builder, or node
*children – Additional children (if first arg is name)
**attrs – Attributes (if first arg is name)
- Returns:
Self for chaining
- children(*children: str | TreeBuilder | Node) TreeBuilder[source]¶
Add multiple children.
- Parameters:
*children – Children to add (names, builders, or nodes)
- Returns:
Self for chaining
- root() TreeBuilder[source]¶
Move to root builder.
- Returns:
Root builder
- up() TreeBuilder[source]¶
Move up to parent builder.
- Returns:
Parent builder (or self if root)
from AlgoTree import TreeBuilder
tree = (TreeBuilder()
.root("app")
.child("config", debug=True)
.sibling("database", host="localhost")
.up()
.child("modules")
.child("auth")
.sibling("api")
.build())
FluentNode¶
from AlgoTree import FluentNode
fluent = FluentNode(tree)
# Chain operations
(fluent
.filter(lambda n: n.payload.get("enabled"))
.map(lambda n: {"processed": True})
.each(lambda n: print(n.name)))
Pattern Matching¶
Pattern¶
PatternMatcher¶
Pattern Functions¶
Closed Transformations (Tree → Tree)¶
Open Transformations (Tree → Any)¶
- AlgoTree.to_dict(children_key: str = 'children') ToDictShaper[source]¶
Create to-dict shaper.
- AlgoTree.to_paths(delimiter: str = '/', to_leaves_only: bool = True) ToPathsShaper[source]¶
Create to-paths shaper.
Tree DSL Parsing¶
- AlgoTree.parse_tree(text: str, format: str = 'auto') Node[source]¶
Convenience function to parse tree from DSL text.
- Parameters:
text – DSL text to parse.
format – Format to use (‘visual’, ‘indent’, ‘sexpr’, ‘auto’).
- Returns:
Root node of parsed tree.
Examples
# Visual format tree = parse_tree(‘’’
company ├── engineering │ ├── frontend │ └── backend └── sales
‘’’)
# Indent format tree = parse_tree(‘’’
- company
- engineering
frontend backend
sales
‘’’)
# S-expression format tree = parse_tree(‘’’
- (company
- (engineering
(frontend) (backend))
(sales))
‘’’)
Export Functions¶
- class AlgoTree.TreeExporter[source]¶
Bases:
objectBase class for tree exporters.
- static to_ascii(node: Node, style: str = 'ascii') str[source]¶
Export tree to ASCII/Unicode art.
- Parameters:
node – Root node of tree
style – “ascii” for ASCII characters, “unicode” for box drawing
- Returns:
String representation of tree
- static to_dict(node: Node) Dict[str, Any][source]¶
Export tree to dictionary (already implemented in Node).
- static to_flat(node: Node, indent: int = 2) str[source]¶
Export tree to flat/graph format.
Creates a flat dictionary where each node is a key mapping to a dict with: - .name: node name (hidden metadata) - .children: list of child node names (hidden metadata) - .color: color attribute if present (hidden metadata) - other attributes as regular key-value pairs
The dot-prefix indicates hidden metadata (like Unix hidden files).
- Parameters:
node – Root node of tree
indent – JSON indentation level
- Returns:
JSON string of flat representation
- static to_graphviz(node: Node, name: str = 'Tree', node_attr: Callable[[Node], Dict[str, str]] | None = None, edge_attr: Callable[[Node, Node], Dict[str, str]] | None = None, graph_attr: Dict[str, str] | None = None) str[source]¶
Export tree to GraphViz DOT format.
- Parameters:
node – Root node of tree
name – Graph name
node_attr – Function to generate node attributes
edge_attr – Function to generate edge attributes
graph_attr – Graph-level attributes
- Returns:
DOT format string
Example
- dot = TreeExporter.to_graphviz(tree,
node_attr=lambda n: {“label”: f”{n.name}n{n.get(‘size’, ‘’)}”})
- static to_html(node: Node, include_styles: bool = True, collapsible: bool = True) str[source]¶
Export tree to interactive HTML.
- Parameters:
node – Root node of tree
include_styles – Include CSS styles
collapsible – Make tree nodes collapsible
- Returns:
HTML string representation
- static to_mermaid(node: Node, direction: str = 'TD', node_shape: str = 'round', node_text: Callable[[Node], str] | None = None) str[source]¶
Export tree to Mermaid diagram format.
- Parameters:
node – Root node of tree
direction – Graph direction (TD, TB, BT, RL, LR)
node_shape – Shape style (“round”, “square”, “circle”, “rhombus”, “stadium”)
node_text – Function to generate node text
- Returns:
Mermaid format string
Example
- mermaid = TreeExporter.to_mermaid(tree,
node_text=lambda n: f”{n.name}<br/>{n.get(‘type’, ‘’)}”)
- static to_unicode(node: Node) str[source]¶
Export tree to Unicode box drawing (alias for to_ascii with unicode style).
- AlgoTree.export_tree(node: Node, format: str, **kwargs) str[source]¶
Export tree to specified format.
- Parameters:
node – Root node of tree
format – Export format (json, ascii, unicode, graphviz, mermaid, yaml, xml, html)
**kwargs – Format-specific options
- Returns:
String representation in specified format
- AlgoTree.save_tree(node: Node, filepath: str, format: str | None = None, **kwargs)[source]¶
Save tree to file in specified format.
- Parameters:
node – Root node of tree
filepath – Output file path
format – Export format (auto-detected from extension if not specified)
**kwargs – Format-specific options
Visualization¶
- AlgoTree.pretty_tree(node, **kwargs) str[source]¶
Converts a tree to a pretty string representation.
- Parameters:
kwargs – Key-word arguments. See PrettyTree for more details.
- Returns:
A pretty string representation of the tree.
- class AlgoTree.PrettyTree(style: ~typing.Dict[str, str] | None = None, node_name: ~typing.Callable[[~typing.Any], str] = <function PrettyTree.<lambda>>, indent: int = 7, mark: ~typing.List[str] | None = None, node_details: ~typing.Callable[[~typing.Any], ~typing.Any] | None = None)[source]¶
Bases:
objectA class to print a tree in a more readable way.
- default_style = {'child_connector': '├', 'horizontal': '─', 'last_child_connector': '└', 'markers': ['🔵', '🔴', '🟢', '🟣', '🟠', '🟡', '🟤', '⚫', '⚪', '⭕', '🔘'], 'payload_connector': '◄', 'spacer': ' ', 'vertical': '│'}¶