AlgoTree package

Subpackages

Submodules

AlgoTree.builders module

Fluent builder API for constructing trees.

This module provides an elegant, chainable API for building trees with a focus on clarity and ease of use.

class AlgoTree.builders.FluentTree(tree: Tree | Node | str)[source]

Bases: object

Fluent wrapper around Tree for chainable operations.

This provides a more fluent API where every operation returns a FluentTree for continued chaining.

filter(predicate: Callable[[Node], bool]) FluentTree[source]

Filter nodes.

find(selector: str | Callable[[Node], bool]) Node | None[source]

Find first matching node.

find_all(selector: str | Callable[[Node], bool]) List[Node][source]

Find all matching nodes.

flatten(max_depth: int | None = None) FluentTree[source]

Flatten tree.

fold(fn: Callable[[Node, List[Any]], Any]) Any[source]

Fold bottom-up.

graft(selector: str | Callable[[Node], bool], subtree: Node | Tree) FluentTree[source]

Graft subtree.

map(fn: Callable[[Node], Node | Dict[str, Any]]) FluentTree[source]

Map function over nodes.

prune(selector: str | Callable[[Node], bool]) FluentTree[source]

Prune nodes.

reduce(fn: Callable[[Any, Node], Any], initial: Any) Any[source]

Reduce to single value.

property root: Node

Get root node.

to_dict(children_key: str = 'children') Dict[str, Any][source]

Export to dictionary.

to_paths() List[str][source]

Export to paths.

transform(transformer: Callable[[Tree], Tree]) FluentTree[source]

Apply custom transformation.

property tree: Tree

Get underlying tree.

class AlgoTree.builders.QuickBuilder[source]

Bases: object

Quick builder for simple tree structures using method chaining.

Example

tree = (

QuickBuilder() .root(‘app’) .add(‘src/main.py’, type=’file’) .add(‘src/utils.py’, type=’file’) .add(‘docs/README.md’, type=’file’) .add(‘tests/test_main.py’, type=’file’) .build()

)

add(path: str, **attrs) QuickBuilder[source]

Add node at path.

build(delimiter: str = '/') Tree[source]

Build tree from paths.

root(name: str, **attrs) QuickBuilder[source]

Set root node.

class AlgoTree.builders.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)

class AlgoTree.builders.TreeContext(name: str, **attrs)[source]

Bases: object

Context manager for building trees with indented syntax.

Example

with TreeContext(‘root’) as ctx:
with ctx.child(‘src’) as src:

src.child(‘main.py’, type=’file’) src.child(‘utils.py’, type=’file’)

with ctx.child(‘docs’) as docs:

docs.child(‘README.md’, type=’file’)

tree = ctx.build()

build() Tree[source]

Build the tree.

child(name: str, **attrs)[source]

Add child in context.

AlgoTree.builders.branch(name: str, *children, **attrs) TreeBuilder[source]

Alias for tree() - creates a branch with children.

AlgoTree.builders.leaf(name: str, **attrs) TreeBuilder[source]

Create a leaf node (no children).

AlgoTree.builders.tree(name: str, *children, **attrs) TreeBuilder[source]

Create tree builder with DSL-style syntax.

Example

my_tree = tree(‘root’,

tree(‘child1’, type=’leaf’), tree(‘child2’,

tree(‘grandchild1’), tree(‘grandchild2’)

)

).build()

AlgoTree.dsl module

DSL (Domain Specific Language) for tree definition.

Supports multiple formats: - Visual tree format (with Unicode box characters) - Indent-based format (YAML-like) - S-expression format

class AlgoTree.dsl.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.

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

‘’’)

AlgoTree.exporters module

Tree export functionality for various formats.

This module provides exporters to convert trees to different representations including GraphViz, Mermaid, ASCII/Unicode trees, and more.

class AlgoTree.exporters.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.exporters.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.exporters.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

AlgoTree.interop module

Interoperability between AlgoTree and AlgoGraph.

Provides conversion functions between tree and graph representations. Trees are special cases of graphs (acyclic, connected, directed from parent to child).

Note: AlgoGraph must be installed or in PYTHONPATH for interop functions to work.

Example

>>> from AlgoTree import Node, tree_to_graph, graph_to_tree
>>> tree = Node('root', Node('child1'), Node('child2'))
>>> graph = tree_to_graph(tree)  # Convert tree to graph
>>> recovered = graph_to_tree(graph, 'root')  # Convert back
AlgoTree.interop.flat_dict_to_node(flat_dict: Dict[str, Any], root_key: str | None = None) Node[source]

Convert flat dictionary format to Node.

This format is compatible with AlgoGraph’s graph_to_flat_dict().

Parameters:
  • flat_dict – Flat dictionary representation

  • root_key – Key of root node (auto-detected if not specified)

Returns:

AlgoTree Node representation

Example

>>> flat = {
...     'A': {'.name': 'A', '.children': ['B', 'C'], 'value': 10},
...     'B': {'.name': 'B', '.children': []},
...     'C': {'.name': 'C', '.children': []}
... }
>>> tree = flat_dict_to_node(flat, 'A')
>>> tree.name
'A'
>>> len(tree.children)
2
AlgoTree.interop.flat_dict_to_tree(flat_dict: Dict[str, Any], root_key: str | None = None)[source]

Convert flat dictionary to Tree.

Parameters:
  • flat_dict – Flat dictionary representation

  • root_key – Key of root node (auto-detected if not specified)

Returns:

AlgoTree Tree object

AlgoTree.interop.graph_to_tree(graph: Graph, root_id: str) Node[source]

Convert AlgoGraph Graph to AlgoTree Node.

Extracts a spanning tree from the graph starting at root_id. Uses BFS traversal to build the tree.

Parameters:
  • graph – AlgoGraph Graph to convert

  • root_id – Vertex ID to use as tree root

Returns:

AlgoTree Node representation (root of tree)

Raises:

ValueError – If root_id not in graph

Example

>>> from AlgoGraph import Graph, Vertex, Edge
>>> from AlgoTree import graph_to_tree
>>> v1, v2, v3 = Vertex('A'), Vertex('B'), Vertex('C')
>>> e1, e2 = Edge('A', 'B'), Edge('A', 'C')
>>> graph = Graph({v1, v2, v3}, {e1, e2})
>>> tree = graph_to_tree(graph, 'A')
>>> tree.name
'A'
>>> len(tree.children)
2
AlgoTree.interop.node_to_flat_dict(node: Node) Dict[str, Any][source]

Convert Node to flat dictionary format.

This format is compatible with AlgoGraph’s flat_dict_to_graph().

The flat format uses: - Keys: node names (with path prefix if duplicates) - Values: dicts with .name, .children, and attributes

Parameters:

node – Root node of tree

Returns:

Flat dictionary representation

Example

>>> from AlgoTree import Node, node_to_flat_dict
>>> tree = Node('A', Node('B'), Node('C', attrs={'value': 10}))
>>> flat = node_to_flat_dict(tree)
>>> flat['A']['.children']
['B', 'C']
>>> flat['C']['value']
10
AlgoTree.interop.tree_to_flat_dict(tree) Dict[str, Any][source]

Convert Tree to flat dictionary format.

Parameters:

tree – AlgoTree Tree object

Returns:

Flat dictionary representation

AlgoTree.interop.tree_to_graph(node: Node, directed: bool = True) Graph[source]

Convert AlgoTree Node (and its subtree) to AlgoGraph Graph.

Each tree node becomes a graph vertex. Parent-child relationships become directed edges.

Parameters:
  • node – Root node of tree (or Tree.root)

  • directed – Whether edges should be directed (default: True)

Returns:

AlgoGraph Graph representation

Example

>>> from AlgoTree import Node, tree_to_graph
>>> tree = Node('root', Node('child1'), Node('child2'))
>>> graph = tree_to_graph(tree)
>>> graph.vertex_count
3
>>> graph.edge_count
2

AlgoTree.node module

Refined immutable-by-default Node implementation.

This module provides the core Node class for AlgoTree with: - Immutability by default for safer, more predictable code - Structural sharing for efficient memory usage - Clean, composable API - Full type hints for IDE support

class AlgoTree.node.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.

AlgoTree.node.node(name: str, *children: Node | str, **attrs) Node[source]

Convenience function to create a node.

Allows mixing Node objects and strings as children. Strings are converted to nodes automatically.

Example

tree = node(‘root’,

node(‘child1’, value=1), ‘child2’, node(‘child3’,

‘grandchild1’, ‘grandchild2’

)

)

AlgoTree.pretty_tree module

class AlgoTree.pretty_tree.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.

AlgoTree.pretty_tree.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.

AlgoTree.selectors module

Composable selector system for tree pattern matching.

This module provides a type-safe, composable selector system that can be combined using logical operators.

class AlgoTree.selectors.AncestorOfSelector(ancestor_selector: Selector, descendant_selector: Selector)[source]

Bases: Selector

Select nodes that are ancestors of descendant matching selector.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.AndSelector(*selectors: Selector)[source]

Bases: Selector

Selector that matches if all sub-selectors match.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.AttrsSelector(**attrs)[source]

Bases: Selector

Select nodes by attributes.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.ChildOfSelector(child_selector: Selector, parent_selector: Selector)[source]

Bases: Selector

Select nodes that are children of parent matching selector.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.DepthSelector(depth: int | range)[source]

Bases: Selector

Select nodes at specific depth.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.DescendantOfSelector(descendant_selector: Selector, ancestor_selector: Selector)[source]

Bases: Selector

Select nodes that are descendants of ancestor matching selector.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.LeafSelector[source]

Bases: Selector

Select leaf nodes.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.NameSelector(pattern: str)[source]

Bases: Selector

Select nodes by name pattern.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.NotSelector(selector: Selector)[source]

Bases: Selector

Selector that matches if sub-selector doesn’t match.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.OrSelector(*selectors: Selector)[source]

Bases: Selector

Selector that matches if any sub-selector matches.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.ParentOfSelector(parent_selector: Selector, child_selector: Selector)[source]

Bases: Selector

Select nodes that are parents of children matching selector.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.PredicateSelector(predicate: Callable[[Node], bool], name: str = 'custom')[source]

Bases: Selector

Select nodes using custom predicate function.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.RootSelector[source]

Bases: Selector

Select root node.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.Selector[source]

Bases: ABC

Abstract base class for tree node selectors.

Selectors can be composed using operators: - & for AND - | for OR - ~ for NOT - ^ for XOR

ancestor_of(descendant_selector: Selector) Selector[source]

Match nodes that are ancestors of nodes matching selector.

at_depth(depth: int) Selector[source]

Match nodes at specific depth.

at_level(level: int) Selector[source]

Alias for at_depth.

child_of(parent_selector: Selector) Selector[source]

Match nodes that are direct children of parent matching selector.

count(tree: Node | Tree) int[source]

Count matching nodes.

descendant_of(ancestor_selector: Selector) Selector[source]

Match nodes that are descendants of nodes matching selector.

exists(tree: Node | Tree) bool[source]

Check if any node matches.

first(tree: Node | Tree) Node | None[source]

Get first matching node or None.

abstractmethod matches(node: Node) bool[source]

Check if node matches this selector.

parent_of(child_selector: Selector) Selector[source]

Match nodes that are direct parents of children matching selector.

select(tree: Node | Tree) Iterator[Node][source]

Select all matching nodes from tree.

sibling_of(sibling_selector: Selector) Selector[source]

Match nodes that are siblings of nodes matching selector.

where(**attrs) Selector[source]

Add attribute constraints.

class AlgoTree.selectors.SiblingOfSelector(node_selector: Selector, sibling_selector: Selector)[source]

Bases: Selector

Select nodes that are siblings of node matching selector.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.TypeSelector(node_type: str)[source]

Bases: Selector

Select nodes by type attribute.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.selectors.XorSelector(*selectors: Selector)[source]

Bases: Selector

Selector that matches if exactly one sub-selector matches.

matches(node: Node) bool[source]

Check if node matches this selector.

AlgoTree.selectors.any_() Selector[source]

Select any node.

AlgoTree.selectors.attrs(**kwargs) AttrsSelector[source]

Create attributes selector.

AlgoTree.selectors.depth(d: int | range) DepthSelector[source]

Create depth selector.

AlgoTree.selectors.leaf() LeafSelector[source]

Create leaf selector.

AlgoTree.selectors.name(pattern: str) NameSelector[source]

Create name selector.

AlgoTree.selectors.none() Selector[source]

Select no nodes.

AlgoTree.selectors.parse(selector_str: str) Selector[source]

Parse CSS-like selector string.

Examples

‘node’ - Select by name ‘*.txt’ - Wildcard pattern ‘[type=file]’ - Attribute selector ‘parent > child’ - Direct child ‘ancestor child’ - Descendant ‘:leaf’ - Pseudo-selectors ‘:root’

AlgoTree.selectors.predicate(fn: Callable[[Node], bool], name: str = 'custom') PredicateSelector[source]

Create predicate selector.

AlgoTree.selectors.root() RootSelector[source]

Create root selector.

AlgoTree.selectors.type_(node_type: str) TypeSelector[source]

Create type selector.

AlgoTree.serialization module

Serialization for AlgoTree - Support for multiple formats.

Supports JSON, YAML, XML, and pickle formats for saving/loading trees.

AlgoTree.serialization.dumps(tree: Node, format: str = 'json', **kwargs) str[source]

Serialize tree to string.

Parameters:
  • tree – Tree to serialize

  • format – Output format (‘json’, ‘yaml’, ‘xml’)

  • **kwargs – Format-specific arguments

Returns:

Serialized string

Example

json_str = dumps(tree, format=”json”, indent=2) yaml_str = dumps(tree, format=”yaml”)

AlgoTree.serialization.from_pickle(data: bytes) Node[source]

Deserialize tree from pickle.

Parameters:

data – Pickled bytes

Returns:

Tree root node

AlgoTree.serialization.load(path: str | Path, format: str | None = None) Node[source]

Load tree from file.

Parameters:
  • path – File path

  • format – Input format (auto-detected from extension if not provided)

Returns:

Root node of loaded tree

Example

tree = load(“tree.json”) tree = load(“tree.yaml”) tree = load(“tree.json.gz”) # Auto-detects compression

AlgoTree.serialization.loads(string: str, format: str = 'json') Node[source]

Deserialize tree from string.

Parameters:
  • string – Serialized string

  • format – Input format (‘json’, ‘yaml’, ‘xml’)

Returns:

Root node of tree

Example

tree = loads(json_str, format=”json”) tree = loads(yaml_str, format=”yaml”)

AlgoTree.serialization.save(tree: Node, path: str | Path, format: str | None = None, compress: bool = False) None[source]

Save tree to file.

Parameters:
  • tree – Tree to save

  • path – File path

  • format – Output format (auto-detected from extension if not provided)

  • compress – If True, use gzip compression

Example

save(tree, “tree.json”) save(tree, “tree.yaml”, format=”yaml”) save(tree, “tree.json.gz”, compress=True)

AlgoTree.serialization.to_pickle(tree: Node) bytes[source]

Serialize tree using pickle.

Parameters:

tree – Tree to serialize

Returns:

Pickled bytes

AlgoTree.transformers module

Composable transformation system for trees.

This module provides a clean, functional approach to tree transformations that can be composed using operators like >> and |.

class AlgoTree.transformers.AnnotateTransformer(selector: Selector | str | Callable[[Node], bool] | None = None, **annotations)[source]

Bases: TreeTransformer

Add annotations to nodes.

class AlgoTree.transformers.ConditionalTransformer(transformer: Transformer[T, S], condition: Callable[[T], bool], else_transformer: Transformer[T, S] | None = None)[source]

Bases: Transformer[T, T | S], Generic[T, S]

Apply transformer conditionally.

class AlgoTree.transformers.DebugTransformer(transformer: Transformer, name: str = '', callback: Callable[[Any], None] | None = None)[source]

Bases: Transformer

Transformer wrapper for debugging.

class AlgoTree.transformers.ExtractShaper(extractor: Callable[[Node], T], selector: Selector | str | Callable[[Node], bool] | None = None)[source]

Bases: Shaper[List[T]]

Extract values from nodes.

class AlgoTree.transformers.FilterTransformer(predicate: Selector | Callable[[Node], bool])[source]

Bases: TreeTransformer

Filter nodes by predicate.

class AlgoTree.transformers.FlattenTransformer(max_depth: int | None = None)[source]

Bases: TreeTransformer

Flatten tree to specified depth.

class AlgoTree.transformers.FoldShaper(fn: Callable[[Node, List[T]], T])[source]

Bases: Shaper[T]

Fold tree bottom-up.

class AlgoTree.transformers.GraftTransformer(selector: Selector | str | Callable[[Node], bool], subtree: Node | Tree | Callable[[Node], Node])[source]

Bases: TreeTransformer

Add subtree to nodes matching selector.

class AlgoTree.transformers.MapTransformer(fn: Callable[[Node], Node | Dict[str, Any] | None])[source]

Bases: TreeTransformer

Map function over all nodes.

class AlgoTree.transformers.NormalizeTransformer(sort_children: bool = True, sort_key: Callable[[Node], Any] | None = None, clean_attrs: bool = False, allowed_attrs: List[str] | None = None)[source]

Bases: TreeTransformer

Normalize tree structure (sort children, clean attributes).

class AlgoTree.transformers.ParallelTransformer(*transformers: Transformer[T, Tree])[source]

Bases: Transformer[T, S], Generic[T, S]

Apply transformers in parallel and merge results.

class AlgoTree.transformers.Pipeline(*transformers: Transformer)[source]

Bases: Transformer[Any, Any]

Sequential composition of transformers.

partial(tree: Any, steps: int) Any[source]

Apply only first N steps of pipeline.

class AlgoTree.transformers.PruneTransformer(selector: Selector | str | Callable[[Node], bool])[source]

Bases: TreeTransformer

Remove nodes matching selector.

class AlgoTree.transformers.ReduceShaper(fn: Callable[[T, Node], T], initial: T, order: str = 'preorder')[source]

Bases: Shaper[T]

Reduce tree to single value.

class AlgoTree.transformers.RepeatTransformer(transformer: Transformer[T, T], times: int)[source]

Bases: Transformer[T, T], Generic[T]

Apply transformer multiple times.

class AlgoTree.transformers.Shaper[source]

Bases: Transformer[Tree, T], Generic[T]

Base class for tree-to-any transformations.

class AlgoTree.transformers.ToDictShaper(children_key: str = 'children')[source]

Bases: Shaper[Dict[str, Any]]

Convert tree to dictionary.

class AlgoTree.transformers.ToPathsShaper(delimiter: str = '/', to_leaves_only: bool = True)[source]

Bases: Shaper[List[str]]

Convert tree to list of paths.

class AlgoTree.transformers.Transformer[source]

Bases: ABC, Generic[T, S]

Base class for composable tree transformations.

Transformers can be composed using operators: - >> or | for sequential composition (pipeline) - & for parallel composition (apply both, merge results)

debug(name: str = '', callback: Callable[[Any], None] | None = None) DebugTransformer[source]

Add debugging to transformer.

repeat(times: int) RepeatTransformer[T][source]

Apply transformer N times.

when(condition: Callable[[T], bool]) ConditionalTransformer[T, S][source]

Apply transformer only if condition is met.

class AlgoTree.transformers.TreeTransformer[source]

Bases: Transformer[Tree, Tree]

Base class for tree-to-tree transformations.

AlgoTree.transformers.annotate(selector: Selector | str | Callable[[Node], bool] | None = None, **annotations) AnnotateTransformer[source]

Create annotate transformer.

AlgoTree.transformers.extract(extractor: Callable[[Node], T], selector: Selector | str | Callable[[Node], bool] | None = None) ExtractShaper[T][source]

Create extract shaper.

AlgoTree.transformers.filter_(predicate: Selector | Callable[[Node], bool]) FilterTransformer[source]

Create filter transformer.

AlgoTree.transformers.flatten(max_depth: int | None = None) FlattenTransformer[source]

Create flatten transformer.

AlgoTree.transformers.fold(fn: Callable[[Node, List[T]], T]) FoldShaper[T][source]

Create fold shaper.

AlgoTree.transformers.graft(selector: Selector | str | Callable[[Node], bool], subtree: Node | Tree | Callable[[Node], Node]) GraftTransformer[source]

Create graft transformer.

AlgoTree.transformers.map_(fn: Callable[[Node], Node | Dict[str, Any] | None]) MapTransformer[source]

Create map transformer.

AlgoTree.transformers.normalize(**kwargs) NormalizeTransformer[source]

Create normalize transformer.

AlgoTree.transformers.prune(selector: Selector | str | Callable[[Node], bool]) PruneTransformer[source]

Create prune transformer.

AlgoTree.transformers.reduce_(fn: Callable[[T, Node], T], initial: T, order: str = 'preorder') ReduceShaper[T][source]

Create reduce shaper.

AlgoTree.transformers.to_dict(children_key: str = 'children') ToDictShaper[source]

Create to-dict shaper.

AlgoTree.transformers.to_paths(delimiter: str = '/', to_leaves_only: bool = True) ToPathsShaper[source]

Create to-paths shaper.

AlgoTree.tree module

Tree wrapper providing functional operations and consistent API.

This module provides a clean, composable API for tree manipulation following functional programming principles.

class AlgoTree.tree.Tree(root: Node | str)[source]

Bases: object

Immutable tree wrapper with fluent, composable API.

All operations return new Tree instances, enabling chaining. The tree itself is never mutated.

count(selector: str | Callable[[Node], bool] | None = None) int[source]

Count nodes matching selector (or all nodes if None).

exists(selector: str | Callable[[Node], bool]) bool[source]

Check if any node matches selector.

filter(predicate: Callable[[Node], bool]) Tree[source]

Filter tree to nodes matching predicate.

Preserves tree structure - keeps ancestors of matching nodes.

Parameters:

predicate – Function that returns True for nodes to keep

Returns:

New filtered tree

find(selector: str | Callable[[Node], bool]) Node | None[source]

Find first node matching selector.

find_all(selector: str | Callable[[Node], bool]) List[Node][source]

Find all nodes matching selector.

flatten(max_depth: int | None = None) Tree[source]

Flatten tree to specified depth.

Parameters:

max_depth – Maximum depth (None for complete flattening)

Returns:

New flattened tree

fold(fn: Callable[[Node, List[T]], T]) T[source]

Fold tree bottom-up, combining child results.

Parameters:

fn – Function (node, child_results) -> result

Returns:

Final folded value

classmethod from_dict(data: Dict[str, Any], children_key: str = 'children') Tree[source]

Create tree from nested dictionary.

Parameters:
  • data – Dictionary with ‘name’ and optional children

  • children_key – Key name for children list

Example

tree = Tree.from_dict({

‘name’: ‘root’, ‘value’: 1, ‘children’: [

{‘name’: ‘child1’, ‘value’: 2}, {‘name’: ‘child2’, ‘value’: 3}

]

})

classmethod from_paths(paths: List[str], delimiter: str = '/') Tree[source]

Create tree from list of paths.

Parameters:
  • paths – List of path strings

  • delimiter – Path delimiter

Example

tree = Tree.from_paths([

‘root/a/b’, ‘root/a/c’, ‘root/d’

])

get_path(path: str, delimiter: str = '/') Node | None[source]

Get node at path.

Parameters:
  • path – Path string (e.g., ‘root/child/grandchild’)

  • delimiter – Path delimiter

Returns:

Node at path or None

graft(selector: str | Callable[[Node], bool], subtree: Node | Tree) Tree[source]

Add subtree to nodes matching selector.

Parameters:
  • selector – Where to graft

  • subtree – Tree or node to graft

Returns:

New tree with subtrees grafted

property height: int

Height of tree.

property is_empty: bool

Check if tree is empty.

property leaves: List[Node]

Get all leaf nodes.

map(fn: Callable[[Node], Node | Dict[str, Any]]) Tree[source]

Map function over all nodes.

Parameters:

fn – Function that takes a node and returns either: - A new node to replace it - A dict of attributes to update - None to keep node unchanged

Returns:

New tree with mapped values

nodes() List[Node][source]

Get all nodes as list.

paths(to_leaves_only: bool = True) List[str][source]

Get all paths in tree.

Parameters:

to_leaves_only – If True, only return paths to leaves

Returns:

List of path strings

prune(selector: str | Callable[[Node], bool]) Tree[source]

Remove nodes matching selector.

Parameters:

selector – Node selector (string pattern or predicate)

Returns:

New tree with nodes pruned

reduce(fn: Callable[[T, Node], T], initial: T, order: str = 'preorder') T[source]

Reduce tree to single value.

Parameters:
  • fn – Reduction function (accumulator, node) -> new_accumulator

  • initial – Initial accumulator value

  • order – Traversal order (‘preorder’, ‘postorder’, ‘levelorder’)

Returns:

Final reduced value

property root: Node

Get root node (immutable).

select(selector: str | Callable[[Node], bool]) Iterator[Node][source]

Select nodes matching selector (returns iterator).

property size: int

Total number of nodes.

to_dict(children_key: str = 'children') Dict[str, Any][source]

Export tree to nested dictionary.

Parameters:

children_key – Key name for children list

Returns:

Nested dictionary representation

to_paths(delimiter: str = '/') List[str][source]

Export tree as list of paths.

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

Walk tree in specified order.

Module contents

AlgoTree - A powerful, modern tree manipulation library for Python.

Core components: - Node: Immutable tree nodes with functional operations - Tree: Tree wrapper with consistent API - Selectors: Composable pattern matching - Transformers: Composable tree transformations - Builders: Fluent API for tree construction

class AlgoTree.AncestorOfSelector(ancestor_selector: Selector, descendant_selector: Selector)[source]

Bases: Selector

Select nodes that are ancestors of descendant matching selector.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.AndSelector(*selectors: Selector)[source]

Bases: Selector

Selector that matches if all sub-selectors match.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.AnnotateTransformer(selector: Selector | str | Callable[[Node], bool] | None = None, **annotations)[source]

Bases: TreeTransformer

Add annotations to nodes.

class AlgoTree.AttrsSelector(**attrs)[source]

Bases: Selector

Select nodes by attributes.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.ChildOfSelector(child_selector: Selector, parent_selector: Selector)[source]

Bases: Selector

Select nodes that are children of parent matching selector.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.ConditionalTransformer(transformer: Transformer[T, S], condition: Callable[[T], bool], else_transformer: Transformer[T, S] | None = None)[source]

Bases: Transformer[T, T | S], Generic[T, S]

Apply transformer conditionally.

class AlgoTree.DebugTransformer(transformer: Transformer, name: str = '', callback: Callable[[Any], None] | None = None)[source]

Bases: Transformer

Transformer wrapper for debugging.

class AlgoTree.DepthSelector(depth: int | range)[source]

Bases: Selector

Select nodes at specific depth.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.DescendantOfSelector(descendant_selector: Selector, ancestor_selector: Selector)[source]

Bases: Selector

Select nodes that are descendants of ancestor matching selector.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.ExtractShaper(extractor: Callable[[Node], T], selector: Selector | str | Callable[[Node], bool] | None = None)[source]

Bases: Shaper[List[T]]

Extract values from nodes.

class AlgoTree.FilterTransformer(predicate: Selector | Callable[[Node], bool])[source]

Bases: TreeTransformer

Filter nodes by predicate.

class AlgoTree.FlattenTransformer(max_depth: int | None = None)[source]

Bases: TreeTransformer

Flatten tree to specified depth.

class AlgoTree.FluentTree(tree: Tree | Node | str)[source]

Bases: object

Fluent wrapper around Tree for chainable operations.

This provides a more fluent API where every operation returns a FluentTree for continued chaining.

filter(predicate: Callable[[Node], bool]) FluentTree[source]

Filter nodes.

find(selector: str | Callable[[Node], bool]) Node | None[source]

Find first matching node.

find_all(selector: str | Callable[[Node], bool]) List[Node][source]

Find all matching nodes.

flatten(max_depth: int | None = None) FluentTree[source]

Flatten tree.

fold(fn: Callable[[Node, List[Any]], Any]) Any[source]

Fold bottom-up.

graft(selector: str | Callable[[Node], bool], subtree: Node | Tree) FluentTree[source]

Graft subtree.

map(fn: Callable[[Node], Node | Dict[str, Any]]) FluentTree[source]

Map function over nodes.

prune(selector: str | Callable[[Node], bool]) FluentTree[source]

Prune nodes.

reduce(fn: Callable[[Any, Node], Any], initial: Any) Any[source]

Reduce to single value.

property root: Node

Get root node.

to_dict(children_key: str = 'children') Dict[str, Any][source]

Export to dictionary.

to_paths() List[str][source]

Export to paths.

transform(transformer: Callable[[Tree], Tree]) FluentTree[source]

Apply custom transformation.

property tree: Tree

Get underlying tree.

class AlgoTree.FoldShaper(fn: Callable[[Node, List[T]], T])[source]

Bases: Shaper[T]

Fold tree bottom-up.

class AlgoTree.GraftTransformer(selector: Selector | str | Callable[[Node], bool], subtree: Node | Tree | Callable[[Node], Node])[source]

Bases: TreeTransformer

Add subtree to nodes matching selector.

class AlgoTree.LeafSelector[source]

Bases: Selector

Select leaf nodes.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.MapTransformer(fn: Callable[[Node], Node | Dict[str, Any] | None])[source]

Bases: TreeTransformer

Map function over all nodes.

class AlgoTree.NameSelector(pattern: str)[source]

Bases: Selector

Select nodes by name pattern.

matches(node: Node) bool[source]

Check if node matches this selector.

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.

class AlgoTree.NormalizeTransformer(sort_children: bool = True, sort_key: Callable[[Node], Any] | None = None, clean_attrs: bool = False, allowed_attrs: List[str] | None = None)[source]

Bases: TreeTransformer

Normalize tree structure (sort children, clean attributes).

class AlgoTree.NotSelector(selector: Selector)[source]

Bases: Selector

Selector that matches if sub-selector doesn’t match.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.OrSelector(*selectors: Selector)[source]

Bases: Selector

Selector that matches if any sub-selector matches.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.ParallelTransformer(*transformers: Transformer[T, Tree])[source]

Bases: Transformer[T, S], Generic[T, S]

Apply transformers in parallel and merge results.

class AlgoTree.ParentOfSelector(parent_selector: Selector, child_selector: Selector)[source]

Bases: Selector

Select nodes that are parents of children matching selector.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.Pipeline(*transformers: Transformer)[source]

Bases: Transformer[Any, Any]

Sequential composition of transformers.

partial(tree: Any, steps: int) Any[source]

Apply only first N steps of pipeline.

class AlgoTree.PredicateSelector(predicate: Callable[[Node], bool], name: str = 'custom')[source]

Bases: Selector

Select nodes using custom predicate function.

matches(node: Node) bool[source]

Check if node matches this selector.

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.

class AlgoTree.PruneTransformer(selector: Selector | str | Callable[[Node], bool])[source]

Bases: TreeTransformer

Remove nodes matching selector.

class AlgoTree.QuickBuilder[source]

Bases: object

Quick builder for simple tree structures using method chaining.

Example

tree = (

QuickBuilder() .root(‘app’) .add(‘src/main.py’, type=’file’) .add(‘src/utils.py’, type=’file’) .add(‘docs/README.md’, type=’file’) .add(‘tests/test_main.py’, type=’file’) .build()

)

add(path: str, **attrs) QuickBuilder[source]

Add node at path.

build(delimiter: str = '/') Tree[source]

Build tree from paths.

root(name: str, **attrs) QuickBuilder[source]

Set root node.

class AlgoTree.ReduceShaper(fn: Callable[[T, Node], T], initial: T, order: str = 'preorder')[source]

Bases: Shaper[T]

Reduce tree to single value.

class AlgoTree.RepeatTransformer(transformer: Transformer[T, T], times: int)[source]

Bases: Transformer[T, T], Generic[T]

Apply transformer multiple times.

class AlgoTree.RootSelector[source]

Bases: Selector

Select root node.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.Selector[source]

Bases: ABC

Abstract base class for tree node selectors.

Selectors can be composed using operators: - & for AND - | for OR - ~ for NOT - ^ for XOR

ancestor_of(descendant_selector: Selector) Selector[source]

Match nodes that are ancestors of nodes matching selector.

at_depth(depth: int) Selector[source]

Match nodes at specific depth.

at_level(level: int) Selector[source]

Alias for at_depth.

child_of(parent_selector: Selector) Selector[source]

Match nodes that are direct children of parent matching selector.

count(tree: Node | Tree) int[source]

Count matching nodes.

descendant_of(ancestor_selector: Selector) Selector[source]

Match nodes that are descendants of nodes matching selector.

exists(tree: Node | Tree) bool[source]

Check if any node matches.

first(tree: Node | Tree) Node | None[source]

Get first matching node or None.

abstractmethod matches(node: Node) bool[source]

Check if node matches this selector.

parent_of(child_selector: Selector) Selector[source]

Match nodes that are direct parents of children matching selector.

select(tree: Node | Tree) Iterator[Node][source]

Select all matching nodes from tree.

sibling_of(sibling_selector: Selector) Selector[source]

Match nodes that are siblings of nodes matching selector.

where(**attrs) Selector[source]

Add attribute constraints.

class AlgoTree.Shaper[source]

Bases: Transformer[Tree, T], Generic[T]

Base class for tree-to-any transformations.

class AlgoTree.SiblingOfSelector(node_selector: Selector, sibling_selector: Selector)[source]

Bases: Selector

Select nodes that are siblings of node matching selector.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.ToDictShaper(children_key: str = 'children')[source]

Bases: Shaper[Dict[str, Any]]

Convert tree to dictionary.

class AlgoTree.ToPathsShaper(delimiter: str = '/', to_leaves_only: bool = True)[source]

Bases: Shaper[List[str]]

Convert tree to list of paths.

class AlgoTree.Transformer[source]

Bases: ABC, Generic[T, S]

Base class for composable tree transformations.

Transformers can be composed using operators: - >> or | for sequential composition (pipeline) - & for parallel composition (apply both, merge results)

debug(name: str = '', callback: Callable[[Any], None] | None = None) DebugTransformer[source]

Add debugging to transformer.

repeat(times: int) RepeatTransformer[T][source]

Apply transformer N times.

when(condition: Callable[[T], bool]) ConditionalTransformer[T, S][source]

Apply transformer only if condition is met.

class AlgoTree.Tree(root: Node | str)[source]

Bases: object

Immutable tree wrapper with fluent, composable API.

All operations return new Tree instances, enabling chaining. The tree itself is never mutated.

count(selector: str | Callable[[Node], bool] | None = None) int[source]

Count nodes matching selector (or all nodes if None).

exists(selector: str | Callable[[Node], bool]) bool[source]

Check if any node matches selector.

filter(predicate: Callable[[Node], bool]) Tree[source]

Filter tree to nodes matching predicate.

Preserves tree structure - keeps ancestors of matching nodes.

Parameters:

predicate – Function that returns True for nodes to keep

Returns:

New filtered tree

find(selector: str | Callable[[Node], bool]) Node | None[source]

Find first node matching selector.

find_all(selector: str | Callable[[Node], bool]) List[Node][source]

Find all nodes matching selector.

flatten(max_depth: int | None = None) Tree[source]

Flatten tree to specified depth.

Parameters:

max_depth – Maximum depth (None for complete flattening)

Returns:

New flattened tree

fold(fn: Callable[[Node, List[T]], T]) T[source]

Fold tree bottom-up, combining child results.

Parameters:

fn – Function (node, child_results) -> result

Returns:

Final folded value

classmethod from_dict(data: Dict[str, Any], children_key: str = 'children') Tree[source]

Create tree from nested dictionary.

Parameters:
  • data – Dictionary with ‘name’ and optional children

  • children_key – Key name for children list

Example

tree = Tree.from_dict({

‘name’: ‘root’, ‘value’: 1, ‘children’: [

{‘name’: ‘child1’, ‘value’: 2}, {‘name’: ‘child2’, ‘value’: 3}

]

})

classmethod from_paths(paths: List[str], delimiter: str = '/') Tree[source]

Create tree from list of paths.

Parameters:
  • paths – List of path strings

  • delimiter – Path delimiter

Example

tree = Tree.from_paths([

‘root/a/b’, ‘root/a/c’, ‘root/d’

])

get_path(path: str, delimiter: str = '/') Node | None[source]

Get node at path.

Parameters:
  • path – Path string (e.g., ‘root/child/grandchild’)

  • delimiter – Path delimiter

Returns:

Node at path or None

graft(selector: str | Callable[[Node], bool], subtree: Node | Tree) Tree[source]

Add subtree to nodes matching selector.

Parameters:
  • selector – Where to graft

  • subtree – Tree or node to graft

Returns:

New tree with subtrees grafted

property height: int

Height of tree.

property is_empty: bool

Check if tree is empty.

property leaves: List[Node]

Get all leaf nodes.

map(fn: Callable[[Node], Node | Dict[str, Any]]) Tree[source]

Map function over all nodes.

Parameters:

fn – Function that takes a node and returns either: - A new node to replace it - A dict of attributes to update - None to keep node unchanged

Returns:

New tree with mapped values

nodes() List[Node][source]

Get all nodes as list.

paths(to_leaves_only: bool = True) List[str][source]

Get all paths in tree.

Parameters:

to_leaves_only – If True, only return paths to leaves

Returns:

List of path strings

prune(selector: str | Callable[[Node], bool]) Tree[source]

Remove nodes matching selector.

Parameters:

selector – Node selector (string pattern or predicate)

Returns:

New tree with nodes pruned

reduce(fn: Callable[[T, Node], T], initial: T, order: str = 'preorder') T[source]

Reduce tree to single value.

Parameters:
  • fn – Reduction function (accumulator, node) -> new_accumulator

  • initial – Initial accumulator value

  • order – Traversal order (‘preorder’, ‘postorder’, ‘levelorder’)

Returns:

Final reduced value

property root: Node

Get root node (immutable).

select(selector: str | Callable[[Node], bool]) Iterator[Node][source]

Select nodes matching selector (returns iterator).

property size: int

Total number of nodes.

to_dict(children_key: str = 'children') Dict[str, Any][source]

Export tree to nested dictionary.

Parameters:

children_key – Key name for children list

Returns:

Nested dictionary representation

to_paths(delimiter: str = '/') List[str][source]

Export tree as list of paths.

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

Walk tree in specified order.

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)

class AlgoTree.TreeContext(name: str, **attrs)[source]

Bases: object

Context manager for building trees with indented syntax.

Example

with TreeContext(‘root’) as ctx:
with ctx.child(‘src’) as src:

src.child(‘main.py’, type=’file’) src.child(‘utils.py’, type=’file’)

with ctx.child(‘docs’) as docs:

docs.child(‘README.md’, type=’file’)

tree = ctx.build()

build() Tree[source]

Build the tree.

child(name: str, **attrs)[source]

Add child in context.

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.

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

class AlgoTree.TreeTransformer[source]

Bases: Transformer[Tree, Tree]

Base class for tree-to-tree transformations.

class AlgoTree.TypeSelector(node_type: str)[source]

Bases: Selector

Select nodes by type attribute.

matches(node: Node) bool[source]

Check if node matches this selector.

class AlgoTree.XorSelector(*selectors: Selector)[source]

Bases: Selector

Selector that matches if exactly one sub-selector matches.

matches(node: Node) bool[source]

Check if node matches this selector.

AlgoTree.annotate(selector: Selector | str | Callable[[Node], bool] | None = None, **annotations) AnnotateTransformer[source]

Create annotate transformer.

AlgoTree.any_() Selector[source]

Select any node.

AlgoTree.attrs(**kwargs) AttrsSelector[source]

Create attributes selector.

AlgoTree.branch(name: str, *children, **attrs) TreeBuilder[source]

Alias for tree() - creates a branch with children.

AlgoTree.depth(d: int | range) DepthSelector[source]

Create depth selector.

AlgoTree.dumps(tree: Node, format: str = 'json', **kwargs) str[source]

Serialize tree to string.

Parameters:
  • tree – Tree to serialize

  • format – Output format (‘json’, ‘yaml’, ‘xml’)

  • **kwargs – Format-specific arguments

Returns:

Serialized string

Example

json_str = dumps(tree, format=”json”, indent=2) yaml_str = dumps(tree, format=”yaml”)

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.extract(extractor: Callable[[Node], T], selector: Selector | str | Callable[[Node], bool] | None = None) ExtractShaper[T][source]

Create extract shaper.

AlgoTree.filter_(predicate: Selector | Callable[[Node], bool]) FilterTransformer[source]

Create filter transformer.

AlgoTree.flat_dict_to_node(flat_dict: Dict[str, Any], root_key: str | None = None) Node[source]

Convert flat dictionary format to Node.

This format is compatible with AlgoGraph’s graph_to_flat_dict().

Parameters:
  • flat_dict – Flat dictionary representation

  • root_key – Key of root node (auto-detected if not specified)

Returns:

AlgoTree Node representation

Example

>>> flat = {
...     'A': {'.name': 'A', '.children': ['B', 'C'], 'value': 10},
...     'B': {'.name': 'B', '.children': []},
...     'C': {'.name': 'C', '.children': []}
... }
>>> tree = flat_dict_to_node(flat, 'A')
>>> tree.name
'A'
>>> len(tree.children)
2
AlgoTree.flat_dict_to_tree(flat_dict: Dict[str, Any], root_key: str | None = None)[source]

Convert flat dictionary to Tree.

Parameters:
  • flat_dict – Flat dictionary representation

  • root_key – Key of root node (auto-detected if not specified)

Returns:

AlgoTree Tree object

AlgoTree.flatten(max_depth: int | None = None) FlattenTransformer[source]

Create flatten transformer.

AlgoTree.fold(fn: Callable[[Node, List[T]], T]) FoldShaper[T][source]

Create fold shaper.

AlgoTree.graft(selector: Selector | str | Callable[[Node], bool], subtree: Node | Tree | Callable[[Node], Node]) GraftTransformer[source]

Create graft transformer.

AlgoTree.graph_to_tree(graph: Graph, root_id: str) Node[source]

Convert AlgoGraph Graph to AlgoTree Node.

Extracts a spanning tree from the graph starting at root_id. Uses BFS traversal to build the tree.

Parameters:
  • graph – AlgoGraph Graph to convert

  • root_id – Vertex ID to use as tree root

Returns:

AlgoTree Node representation (root of tree)

Raises:

ValueError – If root_id not in graph

Example

>>> from AlgoGraph import Graph, Vertex, Edge
>>> from AlgoTree import graph_to_tree
>>> v1, v2, v3 = Vertex('A'), Vertex('B'), Vertex('C')
>>> e1, e2 = Edge('A', 'B'), Edge('A', 'C')
>>> graph = Graph({v1, v2, v3}, {e1, e2})
>>> tree = graph_to_tree(graph, 'A')
>>> tree.name
'A'
>>> len(tree.children)
2
AlgoTree.leaf(name: str, **attrs) TreeBuilder[source]

Create a leaf node (no children).

AlgoTree.load(path: str | Path, format: str | None = None) Node[source]

Load tree from file.

Parameters:
  • path – File path

  • format – Input format (auto-detected from extension if not provided)

Returns:

Root node of loaded tree

Example

tree = load(“tree.json”) tree = load(“tree.yaml”) tree = load(“tree.json.gz”) # Auto-detects compression

AlgoTree.loads(string: str, format: str = 'json') Node[source]

Deserialize tree from string.

Parameters:
  • string – Serialized string

  • format – Input format (‘json’, ‘yaml’, ‘xml’)

Returns:

Root node of tree

Example

tree = loads(json_str, format=”json”) tree = loads(yaml_str, format=”yaml”)

AlgoTree.map_(fn: Callable[[Node], Node | Dict[str, Any] | None]) MapTransformer[source]

Create map transformer.

AlgoTree.name(pattern: str) NameSelector[source]

Create name selector.

AlgoTree.node(name: str, *children: Node | str, **attrs) Node[source]

Convenience function to create a node.

Allows mixing Node objects and strings as children. Strings are converted to nodes automatically.

Example

tree = node(‘root’,

node(‘child1’, value=1), ‘child2’, node(‘child3’,

‘grandchild1’, ‘grandchild2’

)

)

AlgoTree.node_to_flat_dict(node: Node) Dict[str, Any][source]

Convert Node to flat dictionary format.

This format is compatible with AlgoGraph’s flat_dict_to_graph().

The flat format uses: - Keys: node names (with path prefix if duplicates) - Values: dicts with .name, .children, and attributes

Parameters:

node – Root node of tree

Returns:

Flat dictionary representation

Example

>>> from AlgoTree import Node, node_to_flat_dict
>>> tree = Node('A', Node('B'), Node('C', attrs={'value': 10}))
>>> flat = node_to_flat_dict(tree)
>>> flat['A']['.children']
['B', 'C']
>>> flat['C']['value']
10
AlgoTree.none() Selector[source]

Select no nodes.

AlgoTree.normalize(**kwargs) NormalizeTransformer[source]

Create normalize transformer.

AlgoTree.parse(selector_str: str) Selector[source]

Parse CSS-like selector string.

Examples

‘node’ - Select by name ‘*.txt’ - Wildcard pattern ‘[type=file]’ - Attribute selector ‘parent > child’ - Direct child ‘ancestor child’ - Descendant ‘:leaf’ - Pseudo-selectors ‘:root’

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

‘’’)

AlgoTree.predicate(fn: Callable[[Node], bool], name: str = 'custom') PredicateSelector[source]

Create predicate selector.

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.

AlgoTree.prune(selector: Selector | str | Callable[[Node], bool]) PruneTransformer[source]

Create prune transformer.

AlgoTree.reduce_(fn: Callable[[T, Node], T], initial: T, order: str = 'preorder') ReduceShaper[T][source]

Create reduce shaper.

AlgoTree.root() RootSelector[source]

Create root selector.

AlgoTree.save(tree: Node, path: str | Path, format: str | None = None, compress: bool = False) None[source]

Save tree to file.

Parameters:
  • tree – Tree to save

  • path – File path

  • format – Output format (auto-detected from extension if not provided)

  • compress – If True, use gzip compression

Example

save(tree, “tree.json”) save(tree, “tree.yaml”, format=”yaml”) save(tree, “tree.json.gz”, compress=True)

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

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.

AlgoTree.tree(name: str, *children, **attrs) TreeBuilder[source]

Create tree builder with DSL-style syntax.

Example

my_tree = tree(‘root’,

tree(‘child1’, type=’leaf’), tree(‘child2’,

tree(‘grandchild1’), tree(‘grandchild2’)

)

).build()

AlgoTree.tree_to_flat_dict(tree) Dict[str, Any][source]

Convert Tree to flat dictionary format.

Parameters:

tree – AlgoTree Tree object

Returns:

Flat dictionary representation

AlgoTree.tree_to_graph(node: Node, directed: bool = True) Graph[source]

Convert AlgoTree Node (and its subtree) to AlgoGraph Graph.

Each tree node becomes a graph vertex. Parent-child relationships become directed edges.

Parameters:
  • node – Root node of tree (or Tree.root)

  • directed – Whether edges should be directed (default: True)

Returns:

AlgoGraph Graph representation

Example

>>> from AlgoTree import Node, tree_to_graph
>>> tree = Node('root', Node('child1'), Node('child2'))
>>> graph = tree_to_graph(tree)
>>> graph.vertex_count
3
>>> graph.edge_count
2
AlgoTree.type_(node_type: str) TypeSelector[source]

Create type selector.