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

Time:08-24

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?

CodePudding user response:

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()

CodePudding user response:

This is just temporarily possible way try this.

inspect.getmembers(ClassA.ClassB)[0][1]

@Mechanic Pig say right thing. Either this ways is only possible in function is working under structure of ClassA.ClassB.FunctionC

  • Related