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: object

Immutable tree node with functional operations.

All operations return new trees, preserving immutability. Uses structural sharing for efficiency.

ancestors(include_self: bool = False) Iterator[Node][source]

Iterate from this node up to root.

property attrs: Dict[str, Any]

Node attributes (returns copy to prevent mutation).

property children: Tuple[Node, ...]

Children nodes (immutable tuple).

property depth: int

Get depth from root (root has depth 0).

descendants() Iterator[Node][source]

Iterate over all descendants (not including self).

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

get(key: str, default: Any = None) Any[source]

Get attribute with default.

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.

leaves() Iterator[Node][source]

Iterate over all leaf nodes.

map(fn: Callable[[Node], Node]) Node[source]

Apply function to all nodes in tree (bottom-up).

map_children(fn: Callable[[Node], Node]) Node[source]

Return new node with function applied to all children.

property name: str

Node name (immutable).

property parent: Node | None

Parent node (weak reference).

property path: str

Get path from root as string.

siblings() Iterator[Node][source]

Iterate over sibling nodes.

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

walk(order: str = 'preorder') Iterator[Node][source]

Walk tree in specified order.

Parameters:

order – ‘preorder’, ‘postorder’, or ‘levelorder’

with_attrs(**attrs) Node[source]

Return new node with updated attributes.

with_child(child: Node | str, **attrs) Node[source]

Return new node with child added.

with_children(*children: Node) Node[source]

Return new node with children replaced.

with_name(name: str) Node[source]

Return new node with different name.

without_attrs(*keys: str) Node[source]

Return new node with attributes removed.

without_child(child: Node | str | int) Node[source]

Return new node with child removed.

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: object

Fluent 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() Tree[source]

Build the tree.

Returns:

Constructed Tree object

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))

‘’’)

class AlgoTree.TreeDSL[source]

Bases: object

Parser for various tree DSL formats.

static parse(text: str, format: str = 'auto') Node[source]

Parse tree from DSL text.

Parameters:
  • text – DSL text to parse.

  • format – Format to use (‘visual’, ‘indent’, ‘sexpr’, ‘auto’). ‘auto’ tries to detect format automatically.

Returns:

Root node of parsed tree.

Export Functions

class AlgoTree.TreeExporter[source]

Bases: object

Base 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_json(node: Node, indent: int = 2) str[source]

Export tree to JSON string.

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).

static to_xml(node: Node, root_tag: str = 'tree', indent: int = 2) str[source]

Export tree to XML format.

Parameters:
  • node – Root node of tree

  • root_tag – Tag name for root element

  • indent – Number of spaces per level

Returns:

XML string representation

static to_yaml(node: Node, indent: int = 2) str[source]

Export tree to YAML-like indented format.

Parameters:
  • node – Root node of tree

  • indent – Number of spaces per level

Returns:

YAML-like string representation

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: object

A class to print a tree in a more readable way.

default_style = {'child_connector': '├', 'horizontal': '─', 'last_child_connector': '└', 'markers': ['🔵', '🔴', '🟢', '🟣', '🟠', '🟡', '🟤', '⚫', '⚪', '⭕', '🔘'], 'payload_connector': '◄', 'spacer': ' ', 'vertical': '│'}
static mark(name: str, markers: List[str]) str[source]

Get the marker for a node based on the hash of the node name.

Parameters:

name – The name of the node.

Returns:

The marker for the node.