Skip to main content

Abstract base classes for tree data structures

Project description

This Python package contains a few abstract base classes for tree data structures. Trees are very common data structure that represents a hierarchy of common nodes. This package defines abstract base classes for these data structure in order to make code reusable.

Abstract base classes

from abstracttree import to_mermaid

to_mermaid(AbstractTree)
graph TD;
AbstractTree[AbstractTree];
UpTree[UpTree];
Tree[Tree];
MutableTree[MutableTree];
DownTree[DownTree];
Tree[Tree];
MutableTree[MutableTree];
MutableDownTree[MutableDownTree];
MutableTree[MutableTree];
AbstractTree-->UpTree;
UpTree-->Tree;
Tree-->MutableTree;
AbstractTree-->DownTree;
DownTree-->Tree;
DownTree-->MutableDownTree;
MutableDownTree-->MutableTree;

Downtrees are trees that have links to their direct children. Uptrees are trees that link to their parent. A Tree has links in both directions.

ABC Inherits from Abstract Methods Mixin Methods
AbstractTree nid, eqv()
UpTree AbstractTree parent root, is_root, ancestors, path
DownTree AbstractTree children nodes, descendants, leaves, levels, is_leaf, transform()
Tree UpTree, DownTree siblings
MutableDownTree DownTree add_child(), remove_child() add_children()
MutableTree Tree, MutableDownTree detach()

In your own code, you can inherit from these trees. For example, if your tree only has links to children:

import abstracttree
from abstracttree import print_tree

class MyTree(abstracttree.DownTree):
    def __init__(self, value, children=()):
        self.value = value
        self._children = children
    
    def __str__(self):
        return "MyTree " + str(self.value)

    @property
    def children(self):
        return self._children

tree = MyTree(1, children=[MyTree(2), MyTree(3)])
print_tree(tree)

# This generates the following output:
# MyTree 1
# ├─ MyTree 2
# └─ MyTree 3

Adapter

In practice, not all existing tree data structures implement one of these abstract classes. As a bridge, you can use astree to convert these trees to a Tree instance. However, whenever possible, it's recommended to inherit from Tree directly for minimal overhead.

Examples:

# Trees from built-ins and standard library
astree(int)
astree(ast.parse("1 + 1 == 2"))
astree(pathlib.Path("abstracttree"))

# Anything that has parent and children attributes (anytree / bigtree / littletree)
astree(anytree.Node())

# Nested list
astree([[1, 2, 3], [4, 5, 6]])

# Tree from json-data
data = {"name": "a",
        "children": [
            {"name": "b", "children": []},
            {"name": "c", "children": []}
]}
astree(data, children=operator.itemgetter["children"])

# pyqt.QtWidget
astree(widget, children=lambda w: w.children(), parent = lambda w: w.parent())

# Tree from treelib
astree(tree.root, children=lambda nid: tree.children(nid), parent=lambda nid: tree.parent(nid))

# itertree
astree(tree, children=iter, parent=lambda t: t.parent)

# Infinite binary tree
inf_binary = astree(0, children=lambda n: (2*n + 1, 2*n + 2))

Utility functions

Pretty printing

tree = astree(seq, children=lambda x: [x[:-2], x[1:]] if x else [])
print_tree(tree)
print(to_string(tree))

# ['a', 'b', 'c', 'd']
# ├─ ['a', 'b']
# │  └─ ['b']
# └─ ['b', 'c', 'd']
#    ├─ ['b']
#    └─ ['c', 'd']
#       └─ ['d']

Plotting with matplotlib

import matplotlib.pyplot as plt

expr = ast.parse("y = x*x + 1")
plot_tree(expr)
plt.show()

images/tree_calc_plot.png

Conversion to graphviz or mermaid

to_dot(tree)
to_mermaid(tree)

to_image(Path('.'), "filetree.png", how="dot")
to_image(AbstractTree, "class_hierarchy.svg", how="mermaid")
to_pillow(tree).show()

A few concrete tree implementations

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

abstracttree-0.0.2-py3-none-any.whl (17.8 kB view details)

Uploaded Python 3

File details

Details for the file abstracttree-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: abstracttree-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 17.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.11.3 pkginfo/1.8.3 requests/2.28.1 requests-toolbelt/0.9.1 tqdm/4.64.1 CPython/3.10.6

File hashes

Hashes for abstracttree-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 b04fa7b94eb8b933a19a0f0f71c8571804154ac5ff4a4a9367429939581ca099
MD5 b436c6eedff95b6db09be11ac878309f
BLAKE2b-256 363178a012a8055df1bd58f15b99933b49d3d9eb03b5d212f2fea0210a09d777

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page