Figuring out what class instance contains you

Alex VanderWoude alex at computronix.com
Thu Apr 3 23:41:19 EDT 2008


Consider the following module:

================================
class NewDict(dict):
     parent = None

     def __setitem__(self, key, value):
         print "My parent is", self.parent
         super(NewDict, self).__setitem__(key, value)

class Zero(object):
     children = NewDict()

     def __init__(self):
         self.children.parent = self

class One(Zero):
     pass

class Two(One):
     pass

a = One()
a.children["spam"] = "baked beans"
b = Two()
b.children["eggs"] = "bacon"
================================

When the above module is executed, the output looks something like this:

My parent is <__main__.One object at 0x00BA27B0>
My parent is <__main__.Two object at 0x00B9D170>

...which is great, just what I wanted.  Each dictionary instance reports 
correctly which object instance is its container.

However, I would like to find some automagic way of having NewDict 
figure out what object instance it is on without resorting to having the 
container class instance poke a reference to itself into the NewDict 
instance (i.e. the line in Zero.__init__()).

I have tried using inspect.getmembers() and walking up the 
sys._getframe() stack, but to no avail.  Am I missing something here? 
Or is it simply not possible for the NewDict instance to figure out for 
itself what its container is?



More information about the Python-list mailing list