Created
May 10, 2025 22:01
-
-
Save bczsalba/9b62ce5d4cd663413d53f2fdc49dbbe4 to your computer and use it in GitHub Desktop.
python function to get information about caller frames at any given level
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_caller(depth: int = 1): | |
"""Returns the caller frame at the given depth.""" | |
import inspect | |
from collections import namedtuple | |
frame = inspect.currentframe() | |
assert frame is not None | |
if frame.f_back is None: | |
return inspect.getframeinfo(frame) | |
previous_frame = frame | |
for _ in range(depth + 1): | |
f_back = getattr(previous_frame, "f_back") | |
if f_back is None: | |
break | |
previous_frame = f_back | |
filename, lineno, funcname, code, _ = inspect.getframeinfo(previous_frame) | |
return namedtuple("Frame", ["filename", "lineno", "funcname", "code"])( | |
filename, lineno, funcname, code | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment