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

Question:

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?

Asked By: Zigatronz

||

Answers:

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()
Answered By: drewburr

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

Answered By: Lorewalker Cho
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.