Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one find Class of calling function in python?

Tags:

python

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.

like image 250
boldfield Avatar asked Aug 01 '10 19:08

boldfield


1 Answers

Well, if you want to traverse call stack and find which class (if any) did call it, its trivial:

def class_a_method(self):
    stack = inspect.stack()
    frame = stack[1][0]
    caller = frame.f_locals.get('self', None)

If you want to check whether caller is of type ClassB, you should use isinstance(caller, ClassB) rather than comparsion on __class__. However this is generally un-pythonic, since python is duck-typed.

As others stated, most likely your app needs redesign to avoid using inspect.stack. Its CPython implementation feature, and is not guaranteed to be present in other Python implementations. Besides, its just Wrong Thing To Do.

like image 124
Daniel Kluev Avatar answered Oct 26 '22 05:10

Daniel Kluev