Get class of caller's method (via inspect) in Python (alt: super() emulator)

Posted by Slava Vishnyakov on Stack Overflow See other posts from Stack Overflow or by Slava Vishnyakov
Published on 2010-04-24T23:48:00Z Indexed on 2010/04/25 1:13 UTC
Read the original article Hit count: 255

Filed under:

Is it possible to get reference to class B in this example?

class A(object): pass

class B(A):
    def test(self):
        test2()

class C(B): pass

import inspect
def test2():
    frame = inspect.currentframe().f_back
    cls = frame.[?something here?]
    # cls here should == B (class)

c = C()
c.test()

Basically, C is child of B, B is child of A. Then we create c of type C. Then the call to c.test() actually calls B.test() (via inheritance), which calls to test2().

test2() can get the parent frame frame; code reference to method via frame.f_code; self via frame.f_locals['self']; but type(frame.f_locals['self']) is C (of course), but not B, where method is defined.

Any way to get B?

© Stack Overflow or respective owner

Related posts about python