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.


ANSWERS:


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


 MORE:


 ? Python ordinary dictionary to ordered dictionary conversion
 ? Python ordinary dictionary to ordered dictionary conversion
 ? Python ordinary dictionary to ordered dictionary conversion
 ? convert a dict to sorted dict in python
 ? OrderedDict vs Dict in python
 ? How to extract a dictionary in string format as an ordered dictionary?
 ? Are there any reasons not to use an ordered dictionary?
 ? Are there any reasons not to use an ordered dictionary?
 ? Are there any reasons not to use an ordered dictionary?
 ? Is OrderedDict a tree?