For debugging purposes I would like to get the source code of the function that has called my function. So in the following situation:
def calling_func():
x = 123
y = x + 1
myfunc()
def myfunc():
calling_source = f()
I would like a function f, such that calling_source becomes the string
"""
x = 123
y = x + 1
myfunc()
"""
Does such a function exist? I'm guessing that this might be possible with something like sys._current_frames and the inspect module.
asked Feb 10, 2020 at 0:51
MRocklin
57.6k29 gold badges176 silver badges245 bronze badges
2 Answers 2
import sys
import inspect
def called():
print(inspect.getsource(sys._getframe().f_back))
def caller():
called()
x = 123 # Some example code
y = x + 1
caller()
Output:
def caller():
called()
x = 123 # Some example code
y = x + 1
inspect.getsource(object) takes an object as parameter and returns the source code as string.
Sign up to request clarification or add additional context in comments.
Comments
In [1]: import inspect
In [2]: def calling_func():
...: x = 123
...: y = x + 1
...: text = f()
...: print(text)
...:
In [3]: def f() -> str:
...: frame = inspect.currentframe()
...: frame = frame.f_back # go up one in the stack
...: text = inspect.getsource(frame)
...: return text
...:
In [4]: calling_func()
def calling_func():
x = 123
y = x + 1
text = f()
print(text)
answered Feb 10, 2020 at 1:04
MRocklin
57.6k29 gold badges176 silver badges245 bronze badges
Comments
lang-py
strobject? Why not just use a modern debugger in the text editor of your choice with break points etc? Then you can step through the call stack with the source code in front of you.