The following snippet is a simple function for pretty printing trees and other hierarchical data, such as HTML and ASTs.

There's also a version written in Rust.

Output Example

`- Root
   |- Node 1
   |  |- Node 1.1
   |  |  `- Node 1.1.1
   |  |     |- Node 1.1.1.1
   |  |     `- Node 1.1.1.2
   |  |- Node 1.2
   |  |- Node 1.3
   |  |  `- Node 1.3.1
   |  `- Node 1.4
   |     |- Node 1.4.1
   |     `- Node 1.4.2
   |        |- Node 1.4.2.1
   |        `- Node 1.4.2.2
   |           `- Node 1.4.2.2.1
   |- Node 2
   |  |- Node 2.1
   |  `- Node 2.2
   `- Node 3

Snippet

def pprint_tree(node, file=None, _prefix="", _last=True):
    print(_prefix, "`- " if _last else "|- ", node.value, sep="", file=file)
    _prefix += "   " if _last else "|  "
    child_count = len(node.children)
    for i, child in enumerate(node.children):
        _last = i == (child_count - 1)
        pprint_tree(child, file, _prefix, _last)

Parameters

  • node is expected to have two attributes. value which is the value that is printed, and children which is a sequence of child nodes
  • file is simply forwarded to print
  • The _prefix and _last parameters should simply be ignored, they're used between recursive pprint_tree calls

Example

The following example is what produced the output, that was shown in the beginning of the page.

class Node:
    def __init__(self, value=None, children=None):
        if children is None:
            children = []
        self.value, self.children = value, children

tree = Node("Root", [
    Node("Node 1", [
        Node("Node 1.1", [
            Node("Node 1.1.1", [
                Node("Node 1.1.1.1"),
                Node("Node 1.1.1.2"),
            ]),
        ]),
        Node("Node 1.2"),
        Node("Node 1.3", [
            Node("Node 1.3.1")
        ]),
        Node("Node 1.4", [
            Node("Node 1.4.1"),
            Node("Node 1.4.2", [
                Node("Node 1.4.2.1"),
                Node("Node 1.4.2.2", [
                    Node("Node 1.4.2.2.1"),
                ]),
            ]),
        ]),
    ]),
    Node("Node 2", [
        Node("Node 2.1"),
        Node("Node 2.2"),
    ]),
    Node("Node 3"),
])

pprint_tree(tree)