Search code examples
pythoncode-inspectionclass-attributes

How to access a caller method's __class__ attribute from a callee function in Python?


Here __class__ should not be confused with self.__class__ which I am already able to access with the inspect module:

import inspect


class A:

    def __init__(self):
        print(__class__.__name__)  # I want to move this statement inside f
        f()


class B(A):
    pass


def f():
    prev_frame = inspect.currentframe().f_back
    self = prev_frame.f_locals["self"]
    print(self.__class__.__name__)


B()  # prints A B

Solution

  • The implicit __class__ reference is created at compile-time only if you actually reference it within the method (or use super). For example this code:

    class Foo:
        def bar(self):
            print('bar', locals())
    
        def baz(self):
            print('baz', locals())
    
            if False:
                __class__
    
    if __name__ == '__main__':
        foo = Foo()
    
        foo.bar()
        foo.baz()
    

    Produces this output:

    bar {'self': <__main__.Foo object at 0x10f45f978>}
    baz {'self': <__main__.Foo object at 0x10f45f978>, '__class__': <class '__main__.Foo'>}
    

    To find the calling function's class (in most cases) you could chain together a few CPython-specific inspect incantations:

    1. Find the calling function: How to get current function into a variable?
    2. Find that function's class: Get defining class of unbound method object in Python 3

    I wouldn't recommend it.