I would like to build a tree structure that can be constructed easily, without having to remember the exact name of the branch. I know that this question has been discussed here, which solution works fine, but it still requires that the exact name of the key must be remembered. With the following solution I can use autocompletion:
class tree_dot:
""" A class to create a tree structure """
def __init__(self, name):
self.name = name
self.branches = []
def add_branch(self,branch_name):
""" A method to add a branch to the tree which is itself a tree object """
a = tree_dot(branch_name)
setattr(self, branch_name, a)
self.branches.append(a)
The output looking like this:
>>> Tree = tree_dot('Tree')
>>> Tree.add_branch('First')
>>> Tree.First.add_branch('Second')
>>> Tree.First.Second.add_branch('Third')
>>> Tree.First.Second.Third.name = 'This is the third branch !'
However, I feel uncomfortable with such a long name.name.name.name. Does that pose a problem? Is there a better way to do it?