API

Abstract base classes

class abstracttree.tree.AbstractTree[source]

Bases: object

Most abstract baseclass for everything.

classmethod convert(obj)[source]

Convert obj to tree-type or raise TypeError if that doesn’t work.

eqv(other) bool[source]

Check if both objects represent the same node.

Should normally be operator.is, but can be overridden by delegates.

property nid: int

Unique number that represents this node.

class abstracttree.tree.AncestorsView(parent)[source]

Bases: TreeView

class abstracttree.tree.DownTree[source]

Bases: AbstractTree

Abstract class for tree classes with children but no parent.

abstract property children: Collection[TNode]

Children of this node.

property descendants

View of descendants of this node.

property is_leaf: bool

Whether this node is a leaf (does not have children).

property leaves

View of leaves from this node.

property levels

View of this node and descendants by level.

property nodes

View of this node and its descendants.

transform(f: Callable[[TNode], TMutDownNode], keep=None) TMutDownNode[source]

Create new tree where each node of self is transformed by f.

class abstracttree.tree.LeavesView(root)[source]

Bases: TreeView

class abstracttree.tree.MutableDownTree[source]

Bases: DownTree

Abstract class for mutable tree with children.

abstract add_child(node: TNode)[source]

Add node to children.

add_children(children: Iterable[TNode])[source]

Add multiple nodes to children.

abstract remove_child(node: TNode)[source]

Remove node from children.

class abstracttree.tree.MutableTree[source]

Bases: Tree, MutableDownTree

Abstract class for mutable tree with children and parent.

detach() TNode[source]

Remove parent if any and return self.

class abstracttree.tree.NodeItem(index, depth)

Bases: tuple

depth

Alias for field number 1

index

Alias for field number 0

class abstracttree.tree.NodesView(nodes, level)[source]

Bases: TreeView

levelorder(keep=None)[source]

Iterate through nodes in level-order.

Only descend where keep(node). Returns tuples (node, item) Item denotes depth of iteration and index of child.

postorder(keep=None)[source]

Iterate through nodes in post-order.

Only descend where keep(node). Returns tuples (node, item) Item denotes depth of iteration and index of child.

preorder(keep=None)[source]

Iterate through nodes in pre-order.

Only descend where keep(node). Returns tuples (node, item) Item denotes depth of iteration and index of child.

class abstracttree.tree.PathView(node)[source]

Bases: TreeView

count()[source]

Count number of nodes in this view.

class abstracttree.tree.SiblingsView(node)[source]

Bases: TreeView

count()

Count number of nodes in this view.

class abstracttree.tree.Tree[source]

Bases: UpTree, DownTree

Abstract class for tree classes with access to children and parents.

property siblings

View of siblings of this node.

class abstracttree.tree.TreeView[source]

Bases: Iterable[TNode]

count() int[source]

Count number of nodes in this view.

class abstracttree.tree.UpTree[source]

Bases: AbstractTree

Abstract class for tree classes with parent but no children.

property ancestors

View of ancestors of node.

property is_root: bool

Whether this node is a root (has no parent).

abstract property parent: TNode | None

Parent of this node or None if root.

property path

View of path from root to node.

property root: TNode

Root of tree.

class abstracttree.binarytree.BinaryDownTree[source]

Bases: DownTree

Binary-tree with links to children.

property children: Sequence[TNode]

Children of this node.

property descendants

View of descendants of this node.

property nodes

View of this node and its descendants.

class abstracttree.binarytree.BinaryTree[source]

Bases: BinaryDownTree, Tree

Binary-tree with links to children and to parent.

class abstracttree.binarytree.NodesView(nodes, level)[source]

Bases: NodesView

Extend NodesView to make it do inorder.

inorder(keep=None)[source]

Iterate through nodes in inorder (traverse left, yield root, traverse right).

Note: - item.index will be 0 for every left child - item.index will be 1 for every right child (even if node.left_child is None) This is a bit different from how preorder(), postorder() and levelorder() work, because those functions always give index 0 to the first child, regardless of whether it’s a left or right child. Like the other iterators, the root of a subtree always gets item.index equal to 0, even if it is actually a right child in a bigger tree.

Adapters

abstracttree.adapters.astree(obj) Tree[source]
abstracttree.adapters.astree(obj: TWrap, children: Callable[[TWrap], Collection[TWrap]]) Tree
abstracttree.adapters.astree(obj: TWrap, children: Callable[[TWrap], Collection[TWrap]], parent: Callable[[TWrap], TWrap]) Tree

Convert an arbitrary object into a tree.

If no children or parents are given it will try a standard conversion. If children and parents are given, they will be used as a function. If children, but no parent is given, it will create a tree that has obj as its root.

abstracttree.adapters.convert_tree(tree)[source]
abstracttree.adapters.convert_tree(tree: Tree)
abstracttree.adapters.convert_tree(tree: DownTree)
abstracttree.adapters.convert_tree(tree: PurePath)
abstracttree.adapters.convert_tree(zf: ZipFile)
abstracttree.adapters.convert_tree(path: Path)
abstracttree.adapters.convert_tree(tree: Sequence)
abstracttree.adapters.convert_tree(_: str | bytes | bytearray)
abstracttree.adapters.convert_tree(_: str | bytes | bytearray)
abstracttree.adapters.convert_tree(_: str | bytes | bytearray)
abstracttree.adapters.convert_tree(tree: Mapping)
abstracttree.adapters.convert_tree(cls: type, invert=False)
abstracttree.adapters.convert_tree(node: AST)
abstracttree.adapters.convert_tree(element: Element)
abstracttree.adapters.convert_tree(tree: ElementTree)

Low level conversion of tree object to an abstracttree.Tree.

The default implementation ducktypes on tree.parent and tree.children. Classes can also define a method _abstracttree_ to override their conversion.

Export

class abstracttree.export.LiteralText[source]

Bases: str

abstracttree.export.plot_tree(tree: ~abstracttree.tree.Tree, ax=None, formatter=<class 'str'>, keep=MaxDepth(depth=5), annotate_args=None)[source]

Plot the tree using matplotlib (if installed).

abstracttree.export.print_tree(tree, formatter=<class 'str'>, style=None, keep=None)[source]

Print this tree. Shortcut for print(to_string(tree)).

abstracttree.export.to_dot(tree: ~abstracttree.tree.Tree, file=None, keep=MaxDepth(depth=5), node_name: str | ~typing.Callable[[~abstracttree.export.TNode], str] | None = None, node_label: str | ~typing.Callable[[~abstracttree.export.TNode], str] | None = <class 'str'>, node_shape: ~typing.Tuple[str, str] | str | ~typing.Callable[[~abstracttree.export.TNode], ~typing.Tuple[str, str] | str] = None, node_attributes: ~collections.abc.Mapping[str, ~typing.Any] | ~typing.Callable[[~abstracttree.export.TNode], ~collections.abc.Mapping[str, ~typing.Any]] = None, edge_attributes: ~collections.abc.Mapping[str, ~typing.Any] | ~typing.Callable[[~abstracttree.export.TNode, ~abstracttree.export.TNode], ~collections.abc.Mapping[str, ~typing.Any]] = None, graph_attributes: ~collections.abc.Mapping[str, ~typing.Any] = None)[source]

Export to graphviz.

abstracttree.export.to_image(tree: Tree, file=None, how='dot', *args, **kwargs)[source]

Export to image. Uses graphviz(dot) or mermaid.

If file is str or Path, save file under given name. If file is None (default), return image as bytes. If file is writable (binary), write to it.

abstracttree.export.to_latex(tree, file=None, keep=MaxDepth(depth=5), node_label: str | ~typing.Callable[[~abstracttree.export.TNode], str] | None = <class 'str'>, node_shape: ~typing.Tuple[str, str] | str | ~typing.Callable[[~abstracttree.export.TNode], ~typing.Tuple[str, str] | str] = None, leaf_distance: str | None = '2em', level_distance: str | None = None, node_options: ~collections.abc.Iterable[str | ~typing.Callable[[~abstracttree.export.TNode], str]] = (), picture_options: ~collections.abc.Iterable[str | ~typing.Callable[[~abstracttree.export.TNode], str]] = (), graph_direction: str = 'right', indent: str | int = 4, align='center')[source]

Export to latex (experimental).

Make sure to put \usepackage{tikz} in your preamble. Does not wrap output in a figure environment.

abstracttree.export.to_mermaid(tree: ~abstracttree.tree.Tree, file=None, keep=MaxDepth(depth=5), node_name: str | ~typing.Callable[[~abstracttree.export.TNode], str] | None = None, node_label: str | ~typing.Callable[[~abstracttree.export.TNode], str] | None = <class 'str'>, node_shape: ~typing.Tuple[str, str] | str | ~typing.Callable[[~abstracttree.export.TNode], ~typing.Tuple[str, str] | str] = 'box', edge_arrow: str | ~typing.Callable[[~abstracttree.export.TNode, ~abstracttree.export.TNode], str] = '-->', graph_direction: str = 'TD')[source]

Export to mermaid.

abstracttree.export.to_pillow(tree: Tree, **kwargs)[source]

Convert tree to pillow-format (uses graphviz on the background).

abstracttree.export.to_string(tree: ~abstracttree.tree.DownTree, formatter=<class 'str'>, *, file=None, style: str | ~abstracttree.export.Style = 'square', keep=None)[source]

Converts tree to a string in a pretty format.

Predicates

class abstracttree.predicates.MaxDepth(depth: int)[source]

Bases: Predicate

Limit iteration to a certain depth

Can be passed to keep argument of methods such as tree.iter_tree(). >>> from littletree import Node >>> tree = Node(identifier=’root’).path.create([‘a’, ‘b’, ‘c’, ‘d’]).root >>> [node.identifier for node in tree.nodes.preorder(keep=MaxDepth(3))] [‘root’, ‘a’, ‘b’, ‘c’]

class abstracttree.predicates.Predicate[source]

Bases: Callable[[AbstractTree, NodeItem], bool]

class abstracttree.predicates.PredicateIntersection(*preds)[source]

Bases: Predicate

class abstracttree.predicates.PredicateUnion(*preds)[source]

Bases: Predicate

class abstracttree.predicates.PreventCycles[source]

Bases: Predicate

Prevent looping cyclic trees.

It might yield nodes more than once, but will not repeat children. This is mostly useful when trying to plot cyclic trees.

class abstracttree.predicates.RemoveDuplicates[source]

Bases: Predicate

Remove duplicates in case of cycles or multiparent trees.

HeapTree

class abstracttree.heaptree.HeapTree(heap=None, index=0)[source]

Bases: BinaryTree

Provides a tree interface to a heap.

Mainly useful for visualisation purposes. >>> from abstracttree import print_tree >>> import heapq >>> tree = HeapTree() >>> for n in range(5, 0, -1): >>> heapq.heappush(tree.heap, n) >>> print_tree(tree) 0 → 1 ├─ 1 → 2 │ ├─ 3 → 5 │ └─ 4 → 4 └─ 2 → 3

property children: Collection[TNode]

Children of this node.

eqv(other)[source]

Check if both objects represent the same node.

Should normally be operator.is, but can be overridden by delegates.

property nid

Unique number that represents this node.

property parent: TNode | None

Parent of this node or None if root.

Route

class abstracttree.route.Route(*anchors: TNode)[source]

Bases: object

Representation of a route trough adjacent nodes in the tree.

Two nodes are adjacent if they have a parent-child relationship. The route will be as short as possible, but it will visit the anchor points in order.

add_anchor(anchor: TNode)[source]

Add a node to the route.

The node should belong to the same tree as any existing anchor nodes.

property anchors

View of the anchor nodes.

property edges

View of all edges that make up the route.

property lca: TNode | None

The least common ancestor of all anchor nodes.

property nodes

View of all nodes that make up the route.