Search code examples
pythonpython-3.xpython-class

Python: How to get all the parent classes and function names in one array within that function


What I tried:

import inspect

class ClassA:
    class ClassB:
        def FunctionC():
            print(inspect.stack()[0][3])    # returns 'FunctionC'

ClassA.ClassB.FunctionC()

This only returns the current function name, what I need is all the parent classes and function names inside one array. I mean something like this:

output = ['ClassA', 'ClassB', 'FunctionC']

Is it possible?


Solution

  • Looks like inspect.stack() has an code_context attribute that contains this information. This can also be accessed through inspect.stack()[1][4], if you'd prefer.

    import inspect
    
    class ClassA:
        class ClassB:
            @staticmethod
            def FunctionC():
                context = inspect.stack()[1].code_context[0].replace('\n', '')
                print(context.split('.'))
    
    
    ClassA.ClassB.FunctionC()