Package: abstracttree
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 classesfromabstracttreeimportto_mermaidto_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.ABCInherits fromAbstract MethodsMixin MethodsAbstractTreenid,eqv()UpTreeAbstractTreeparentroot,is_root,ancestors,pathDownTreeAbstractTreechildrennodes,descendants,leaves,levels,is_leaf,transform()TreeUpTree,DownTreesiblingsMutableDownTreeDownTreeadd_child(),remove_child()add_children()MutableTreeTree,MutableDownTreedetach()In your own code, you can inherit from these trees.
For example, if your tree only has links to children:importabstracttreefromabstracttreeimportprint_treeclassMyTree(abstracttree.DownTree):def__init__(self,value,children=()):self.value=valueself._children=childrendef__str__(self):return"MyTree "+str(self.value)@propertydefchildren(self):returnself._childrentree=MyTree(1,children=[MyTree(2),MyTree(3)])print_tree(tree)# This generates the following output:# MyTree 1# ├─ MyTree 2# └─ MyTree 3AdapterIn practice, not all existing tree data structures implement one of these abstract classes.
As a bridge, you can useastreeto convert these trees to aTreeinstance.
However, whenever possible, it's recommended to inherit fromTreedirectly for minimal overhead.Examples:# Trees from built-ins and standard libraryastree(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 listastree([[1,2,3],[4,5,6]])# Tree from json-datadata={"name":"a","children":[{"name":"b","children":[]},{"name":"c","children":[]}]}astree(data,children=operator.itemgetter["children"])# pyqt.QtWidgetastree(widget,children=lambdaw:w.children(),parent=lambdaw:w.parent())# Tree from treelibastree(tree.root,children=lambdanid:tree.children(nid),parent=lambdanid:tree.parent(nid))# itertreeastree(tree,children=iter,parent=lambdat:t.parent)# Infinite binary treeinf_binary=astree(0,children=lambdan:(2*n+1,2*n+2))Utility functionsPretty printingtree=astree(seq,children=lambdax:[x[:-2],x[1:]]ifxelse[])print_tree(tree)print(to_string(tree))# ['a', 'b', 'c', 'd']# ├─ ['a', 'b']# │  └─ ['b']# └─ ['b', 'c', 'd']#    ├─ ['b']#    └─ ['c', 'd']#       └─ ['d']Plotting with matplotlibimportmatplotlib.pyplotaspltexpr=ast.parse("y = x*x + 1")plot_tree(expr)plt.show()Export to various formatsto_dot(tree)to_mermaid(tree)to_latex(tree)to_image(Path('.'),"filetree.png",how="dot")to_image(AbstractTree,"class_hierarchy.svg",how="mermaid")to_pillow(tree).show()Find distance between nodesimportheapqfromabstracttreeimportHeapTree,Routetree=HeapTree([5,4,3,2,1])heapq.heapify(tree.heap)left_child=tree.children[0]right_child=tree.children[1]route=Route(left_child,right_child)print(f"{route.lca= }")# => HeapTree([1, 2, 3, 5, 4], 0)print(f"{route.nodes.count()= }")# => 3print(f"{route.edges.count()= }")# => 2A few concrete tree implementationsanytreetreelibbigtreeitertreedendropyetelittletree- also by meTree visualisationPrettyPrintTree- colored terminal output