Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Python Object Parent?

So, I'm trying to get the object that a custom object is 'inside' of. Here's an example.

Assume that o is an object - it doesn't matter what kind, it can just store variables.

o = Object()
class Test():
    def __init__(self):
        self.parent = o ## This is where I fall off; I want to be able to access
                        ## the o object from within the Test object

o.test = Test()

So, how would I get o from inside of Test? I know I could write the Test function to pass it in with

o.test = Test(o)

but I'd rather do it from inside the class definition.

like image 767
SolarLune Avatar asked Dec 05 '22 21:12

SolarLune


2 Answers

(I know this is an old question but since it's unanswered...)
You could try messing with the garbage collector. Was going to suggest looking at the module level objects but some quick code experimentation gave this: Try the gc.get_referrers(*objs) function.

import gc

class Foo(object):
    """contains Bar"""
    def __init__(self, val):
        self.val = val
        self.bar = None

class Bar(object):
    """wants to find its parents"""
    def __init__(self, something):
        self.spam = something

    def find_parents(self):
        return gc.get_referrers(self)

The results aren't straightforward so you'll have to apply your own logic for how determine which f is the one you're looking for. Notice the 'f': <__main__.Foo object at ...> below:

>>> f = Foo(4)
>>> b = Bar('ham')
>>> f.bar = b
>>> b.find_parents()
[{'bar': <__main__.Bar object at 0x7f3ec5540f90>, 'val': 4}, <frame object at 0x238c200>,
{'b': <__main__.Bar object at 0x7f3ec5540f90>,
    'Bar': <class '__main__.Bar'>,
    'f': <__main__.Foo object at 0x7f3ec5540f10>,    # <-- these might be
                                          # the droids you're looking for
    '__builtins__': <module '__builtin__' (built-in)>,
    '__package__': None, 'gc': <module 'gc' (built-in)>, '__name__': '__main__',
    'Foo': <class '__main__.Foo'>, '__doc__': None
}]

For bonus points, use gc.get_referents(*objs) on those to check if the same b is in their list.

Some notes/caveats:

  • I think you should just pass the parent Foo object to Bar, either in init or another method. That's what I would do, instead of my suggestion above.
  • This SO answer points out some issues the garbage collector has when linking both ways - you're not currently doing that but if you do, fyi.
like image 122
aneroid Avatar answered Dec 07 '22 11:12

aneroid


you could do something like this:

class Object:
    def __setattr__(self, name, value):
        if isinstance(value, Test):
            value.set_parent(self)
        self.__dict__[name] = value

class Test:
    def set_parent(self, parent):
        self.parent = parent

o = Object()
o.test = Test()
assert o.test.parent is o
like image 42
Dan D. Avatar answered Dec 07 '22 10:12

Dan D.