Accessing python container's parent object
Question: I need to create a containers that can access its children but also its
parent. Here is a simple example of how I was thinking to do that :

    
    
    import numpy as np
    import gc
    
    
    class Node(object):
    
        def __init__(self, name):
            self.parent = None
            self.child = []
            self.name = name
            self.mem_tracer = np.ones(10 ** 6)
    
        def append(self, obj):
            assert(isinstance(obj, Node))
            self.child.append(obj)
            obj.parent = self
    

But, with that I have a memory issue when I try to delete a Node (note that
the attribute mem_tracer is just here to be able to see if the object has been
removed from the memory or not)

This code shows the problem (the memory state at each line is given) :

    
    
    print 'start'                    # 16.96Mb
    
    a = Node('0')                    # 24.79Mb
    
    a.append(Node('0/0'))            # 32.61Mb
    a.append(Node('0/1'))            # 40.42Mb
    
    a.child[0].append(Node('0/0/0')) # 48.24Mb
    a.child[0].append(Node('0/0/1')) # 56.06Mb
    
    a.child[1].append(Node('0/1/0')) # 63.87Mb
    a.child[1].append(Node('0/1/1')) # 71.69Mb
    
    del a.child[0]                   # 71.69Mb
    
    gc.collect()                     # 48.24Mb
    

The garbage collector is not able to collect the deleted object as a reference
to it still exists in its children (while they are not referenced anywhere
anymore). We can see at the last line, that an explicit call to `gc.collect`
solves the problem but I would prefer to get rid of it as it is very time
consuming!

So is there an other way to access the parent container than storing it into
an attribute? Thanks in advance.


Answer: You have two choices:

  * manually delete `obj.parent`
  * use `weakref` to keep a pseudo-reference to the parent.

See [the docs](https://docs.python.org/3/library/weakref.html#module-weakref)
for more info on `weakref`.

