Search code examples
pythonpython-2.7treepretty-printpprint

How to pprint a tree data structure that is implemented using classes?


I know that pprint can pretty-print a nested list or dictionary, which are both types of tree structures, but I want to pprint a class-based tree with an arbitrary number of children, such that nodes are indented to the right depending on their level in the tree.

Can pprint be used to do what I want, and if so, how? I can write my own function that pretty-prints a tree, but I wanted to check if I even need to do that.

Consider the following example:

class Tree:
    def __init__(self, value, *args):
        self.value = value
        self.children = args

tree = Tree("+", Tree(1), Tree("*", Tree(2), Tree(3)))

Here is my expected output, if we were to pretty-print the tree:

+
    1
    *
        2
        3

Again, I can certainly roll my own function, but I want to see if I can use pprint instead if that would be easier and I'm just overlooking something.

The pprint documentation doesn't provide an example for my use case.

If it makes a difference, I'm using Python 2.7.


Solution

  • pprint works with arbitrary classes that have defined their __repr__ method.

    To get what you want here, I think you would have to manage your own nesting, at which point you could just use print.

    def __repr__(self, depth=1):
        return_string = [str(self.value)]
        for child in self.children:
            return_string.extend(["\n", " " * (depth+1), child.__repr__(depth+1)])
        return "".join(return_string)
    

    and then pprint(tree) and print tree both give you

    +
      1
      *
       2
       3