I am trying to determine the owning class of a calling function in python. For example, I have two classes, ClassA and ClassB. I want to know when classb_instance.call_class_a_method() is the caller of class_a.class_a_method() such that:
class ClassA(object):
def class_a_method(self):
# Some unknown process would occur here to
# define caller.
if caller.__class__ == ClassB:
print 'ClassB is calling.'
else:
print 'ClassB is not calling.'
class ClassB(object):
def __init__(self):
self.class_a_instance = ClassA()
def call_class_a_method(self):
self.class_a_instance.class_a_method()
classa_instance = ClassA()
classa_instance.class_a_method()
classb_instance = ClassB()
classb_instance.call_class_a_method()
the output would be:
'ClassB is not calling.'
'ClassB is calling.'
It seems as though inspect should be able to do this, but I cant puzzle out how.
A function does not “have” a class — one or more classes may (but need not) refer to a given function object, e.g.:
One.bahandTwo.blupare both set as references to the same function objectf(and turn into unbound or bound method objects when accessed on the classes or their instances, but that leaves no trace in the stack). So, the stack uponvs
as seen from the
g()that’s called in either case, is pretty hard indeed to distinguish — as would be that resulting from, e.g.,with no “classes” involved at all (though the type of the string being used as
f‘sselfargument would be;-).I recommend not relying on introspection — especially the wild and wooly kind, with lots of heuristics, that would be needed to get any semi-useful info here — for any production code requirements: rearchitect to avoid that need.
For purely debugging purposes, in this case, you could walk the stack until you find a calling function with a first argument named
selfand introspect the type of the value bound to that argument name — but as I mentioned that’s entirely heuristical, since nothing forces your callers to name their first argumentselfif and only if their functions are meant to be methods in some class.Such heuristic introspection would produce type objects
One,Two, andstr, in the three examples of code I just gave — as you see, definitely not good for much else than debugging;-).If you clarify better exactly what you’re trying to accomplish through this attempted introspection, we might of course be able to help you better.