Getting container/parent object from within python

Pass a reference to the Bar object, like so:

class Foo(object):
    def __init__(self):
        self.text = "Hello World"  # has to be created first, so Bar.__init__ can reference it
        self.bar = Bar(self)

class Bar(object):
    def __init__(self, parent):
        self.parent = parent
        self.newText = parent.text

foo = Foo()

Edit: as pointed out by @thomleo, this can cause problems with garbage collection. The suggested solution is laid out at http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/ and looks like

import weakref

class Foo(object):
    def __init__(self):
        self.text = "Hello World"
        self.bar = Bar(self)

class Bar(object):
    def __init__(self, parent):
        self.parent = weakref.ref(parent)    # <= garbage-collector safe!
        self.newText = parent.text

foo = Foo()

Leave a Comment