Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading