jt_reed
jt_reed

Reputation: 27

How to get the object who instantiated a class

I have the following situation: I have multiple classes who gets instantiated everywhere in my application. I want every object to get an id from the parent object (saying that I have object B and object B instantiate object C then object B is the parent of object C but object C can be also parent for other objects, i'm not talking inheritance).

What I can guarantee is that all classes inherits from the same base class, let's say rootobject class and I can work on this.

I really want to avoid refactoring object instantiation since there are a huge amount of classes. Passing the self argument when object is instantiated is not an option, is too time consuming when you have a large code base.

I thought about an way on looking to the call stack frames and try to get from there the class who instantiated "me". It should be the previous frame but this implementation is too hackish.

Any ideas ?

Upvotes: 2

Views: 222

Answers (1)

orlp
orlp

Reputation: 117681

This is a very hacky, but working solution:

import inspect

def get_instantiator():
    # The instantiator is two frames back.
    frame = inspect.currentframe().f_back.f_back
    frame_args = inspect.getargvalues(frame)
    return frame_args.locals[frame_args.args[0]]

class A:
    def __init__(self):
        self.b = B()

class B:
    def __init__(self):
        self.parent = get_instantiator()

a = A()
print(a.b.parent == a)

It finds the self argument passed into the instantiating class.

Upvotes: 2

Related Questions