Skip to content

Instantly share code, notes, and snippets.

@johnhw
Created July 8, 2019 16:09
Show Gist options
  • Save johnhw/1ded25ae45570f9e3bbd83156174f3b2 to your computer and use it in GitHub Desktop.
Save johnhw/1ded25ae45570f9e3bbd83156174f3b2 to your computer and use it in GitHub Desktop.
Determine source of function calls in Python
import inspect
class tracked:
"""Class to remember the execution frame
that a function call was made in."""
def __init__(self, fn):
self.fn = fn
def __call__(self, *args, **kwargs):
# remember this frame
self.frame = inspect.currentframe().__hash__()
self.fn(*args, **kwargs)
def track(track):
"""Wrap a function call, taking a "tracked" object as
a reference to an execution frame, and print the lines
of code where the traceback intersects with that execution frame."""
def wrap(fn):
def _track(*args, **kwargs):
frames = inspect.getouterframes(inspect.currentframe())
# step back through each outer frame
for i, frame in enumerate(frames):
# found our match?
if frame[0].__hash__()==track.frame:
ix = i
break
# show the line of code for the frame outside of the matching frame
if ix is not None:
print(frames[ix-1].code_context, "line", frames[ix-1].lineno)
return fn(*args, **kwargs)
return _track
return wrap
@tracked
def f():
x = g()
y = g()
@track(f)
def g():
print("Hey")
f()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment