pptree: Pretty print trees

3.1 · maintenance · verified Thu Apr 16

pptree is a Python library (current version 3.1) designed to pretty-print tree-like data structures in a console-friendly, hierarchical format. It provides a default `Node` implementation and a `print_tree` function that can work with both its own `Node` objects and custom object structures. The library has an infrequent release cadence, with the last update in April 2020.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create and pretty-print a tree using `pptree`'s default `Node` class and how to adapt `print_tree` for custom node implementations by specifying `childattr` and `nameattr`.

from pptree import Node, print_tree

# Create a tree using the default Node class
root = Node("Root")
child1 = Node("Child 1", root)
child2 = Node("Child 2", root)
grandchild1 = Node("Grandchild 1", child1)

print("--- Default Node Tree ---")
print_tree(root)

# Example with custom node class
class CustomNode:
    def __init__(self, name, parent=None):
        self.custom_name = name
        self.children_list = []
        if parent:
            parent.children_list.append(self)

    def __str__(self):
        return self.custom_name

custom_root = CustomNode("Custom Root")
custom_child1 = CustomNode("Custom Child 1", custom_root)
custom_child2 = CustomNode("Custom Child 2", custom_root)

print("\n--- Custom Node Tree ---")
# For custom nodes, specify 'childattr' and 'nameattr'
print_tree(custom_root, childattr='children_list', nameattr='custom_name')

view raw JSON →