1

I am trying to trace a hierarchy of function calls of a given function (traceback) but in a way that would allow me to get a reference to a class which holds a function as attribute. Getting a reference of the class instance would be nice too.

If I have an object of class A which has function do_work and function do_work calls a function f, I want to know inside f which instance of A called it.

Currently, using the inspect module I get the correct order of function calls, but this does not include any reference to the class or object instance holding the function as an attribute:

import inspect


class A:
    def __init__(self, name):
        self.name = name

    def do_work(self):
        return f()


def f():
    return inspect.stack()


a = A("test")
print(a.do_work())
[
FrameInfo(frame=<... line 13, code f>, code_context=['return inspect.stack()'])
FrameInfo(frame=<..., line 9, code do_work>, code_context=['return f()']),
FrameInfo(frame=<..., line 17, code <module>>, code_context=['print(a.do_work())'])
]

I would like to get a reference from f to the a object instance or at least to the A class.

afrendeiro
  • 2,423
  • 2
  • 23
  • 22

1 Answers1

1

Given the FrameInfo for the frame you're interested in:

frame_info = inspect.stack()[1]
# FrameInfo(frame=<frame at 0x107b959d8, file ..., line 8, code do_work>, filename='...', lineno=8, function='do_work', code_context=['        return f()\\n'], index=0)

You can get to the a object (which is known as self in that frame) via:

frame_info.frame.f_locals['self']
# <__main__.A object at 0x107b86a20>

And to its class name using:

frame_info.frame.f_locals['self'].__class__.__name__
# A
Nickolay
  • 31,095
  • 13
  • 107
  • 185