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.
(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:
init
or another method. That's what I would do, instead of my suggestion above.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With