Skip to content

Instantly share code, notes, and snippets.

@encukou
Created August 8, 2023 16:14
Show Gist options
  • Save encukou/b0c0396d2072e1aa63015e7c6471398e to your computer and use it in GitHub Desktop.
Save encukou/b0c0396d2072e1aa63015e7c6471398e to your computer and use it in GitHub Desktop.
import inspect
import sys
import functools
def trace(f):
signature = inspect.signature(f)
indent = ''
@functools.wraps(f)
def decorated(*a, **ka):
nonlocal indent
bound = signature.bind(*a, **ka)
#bound.apply_defaults()
bound_repr = ', '.join(
f'{name}={value!r}' for name, value in bound.arguments.items()
)
print(f'{indent}Entering {f.__name__}({bound_repr})')
indent += ' '
result = f(*a, **ka)
indent = indent[:-2]
print(f'{indent}Exiting {f.__name__}({bound_repr}) = {result}')
return result
return decorated
#trace
def fib(n, foo=1):
if n <= 1:
return 1
a = 3
return fib(n-1) + fib(n-2)
indent = ''
def tracefunc(frame, event, arg):
global indent
if event == 'call':
print(f'{indent}Entering {frame.f_code.co_name}({frame.f_locals})')
indent += ' '
if event == 'return':
indent = indent[:-2]
print(f'{indent}Exiting {frame.f_code.co_name}(...) = {arg}')
if event == 'line':
print(f'{indent}{frame.f_lineno} ({frame.f_code.co_filename})')
return tracefunc
sys.settrace(tracefunc)
for i in range(10):
print(i, fib(i))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment