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.