Search code examples
pythonpython-3.xrecursiontreerepr

Self defined __repr__ for pretty print in Python


I have got a piece of code from here, about using the __repr__ to get kind of pretty print. However, I want to modify this code, because while using it in a loop, I always got error: maximum recursion depth exceeded

The problem is, I do not know how to modify it, because I do not understand this self-defined __repr__ clearly, even I have read some of explanations from here.

Code:

class node(object):
    def __init__(self, value):
        self.value = value
        self.children = []

    def __repr__(self, level=0):
        ret = "\t"*level+repr(self.value)+"\n"
        for child in self.children:
            ret += child.__repr__(level+1)
        return ret

My quesiton:

  1. is the repr the same as the __repr__ in the recursion?
  2. is the variable level indicates the recursion depth?
  3. what is the purpose of this line ret += child.__repr__(level+1) ?

My purpose of using this code: to traverse a tree and print somewhat like follows:

'grandmother'
    'daughter'
        'granddaughter'
        'grandson'
    'son'
        'granddaughter'
        'grandson'

Very confused about the recursion part, appreciate any comment, thanks!


Solution

  • repr doesn't do anything except call its argument's __repr__ method. Since self.value is likely not an instance of node, self.value.__repr__ is not a recursive call.

    child.__repr__, for all practical purposes, is a recursive call, so you are correct that level is a measure of the "depth" of the current call in the recursion tree.

    ret is just the concatenation of each child's representation. Those, combined with the representation of the root, produces the representation of the entire tree rooted at the current node.