Skip to content

Instantly share code, notes, and snippets.

@bczsalba
Created May 10, 2025 22:01
Show Gist options
  • Save bczsalba/9b62ce5d4cd663413d53f2fdc49dbbe4 to your computer and use it in GitHub Desktop.
Save bczsalba/9b62ce5d4cd663413d53f2fdc49dbbe4 to your computer and use it in GitHub Desktop.
python function to get information about caller frames at any given level
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