Search code examples
pythonparentparent-childhierarchy

best way to represent a bidirectional traversable hierarchy


I need to represent some data as a hierarchy where an object can have one parent and many children. I also need to be able to get a child's parent in the same way that i would a child.

I tried this

class Root():
    def __init__(self):
        self.child = Node(self)

class Node():
    def __init__(self, parent):
        self.parent = parent

Is there a common way of solving this problem out there


Solution

  • I think that this is basically how Tkinter does it:

    class Root(object):
        def __init__(self):
            self.children = []
    
    class Node(object):
       def __init__(self,parent):
            self.parent = parent
            parent.children.append(self)
    

    Now, Root knows all it's children via the children attribute, and the children know their parents via the parent attribute.

    r = Root()
    n = Node(r)
    r.children[0] is n  #True
    n.parent is r  #True
    

    Of course, you could make things a little more interesting by giving Node objects a children attribute as well -- Then Nodes can parent more Nodes. Neat.

    There are some downsides here (mainly cyclic references). If you want to avoid that, you could use weakref.refs to store the references to the children/parents, but I'll defer that to another question if necessary.