Get reference to Caller from Callee

Is there some built-in way in Python to get a reference to the ‘Callers’ instance? We know this must be stored in Python somewhere otherwise it wouldn’t know where to send the the return value to. Sure it could be passed as a parameter but why go to that overhead as it already exists somewhere. See example code:

class Callee():
    def method(self):
        print("Caller.ClassVar:", Caller.ClassVar)
        # print("Caller.InstVar:", Caller.InstVar) # <- this fails because instance of Caller is not available
        return "retVal"

class Caller():
    ClassVar = "var1"
    def __init__(self):
        self.InstVar = "var2"
        oCallee = Callee()
        print("return from oCallee.method():", oCallee.method())

oCaller = Caller()

The inspect module

While you might be able to inspect the stack and figure out which function the immediate caller was executing, and figure out if it was a method and which instance of which class, it would be fragile. What happens when Callee.method() is called from some other function? Whatever you come up with will be far more complex and fragile than just passing the information you need to the method.

So, while you may be able to do what you think you want to do, it is a bad idea. Be explicit. Pass the information the method needs, don’t try to infer it. Passing it will be much less “overhead” than digging it up out of the call stack.