The pattern you are going to want to use is to have nodes that keep track of their children, and then use a recursive function to do the printing.
The basic idea of it is this:
class Node():
def __init__(self, name, children=[]):
self.children = children
self.name = name
def print(self, level=0):
print('\t'*level, self.name)
level += 1
for child in self.children:
child.print(level)
a = Node('parent', [ Node('child', [ Node('grandchild') ]) ])
a.print()
But to get the exact output in you were wanting, you would need to do something like this:
class Node():
def __init__(self, name, children=[]):
if not isinstance(children, list):
children = [children]
self.children = children
self.name = name
def print(self, level=0, special_print=False):
''' Recursively print out all of the children in a nice visual way.
level keeps track of the indentation as we go along.
special_print prefixes the outputted line with a bunch of --- followed by a |
This special printing happens whenever there is a change in indentation '''
if level is 0:
print(self.name)
elif special_print:
print('----------'*level + '|' + self.name)
else:
print(' '*level + ' ' + self.name)
level += 1
special_print = True
for child in self.children:
child.print(level, special_print)
special_print = bool(child.children)
a = Node('parent_data', [
Node('child_data'),
Node('child_data'),
Node('child_data', [
Node('grandchild'),
Node('grandchild')
]),
Node('child_data'),
])
a.print()