Use a decorator to trace your functions
Our goal is to create a reusable way to trace functions in Python. We do this by coding a decorator with Python’s functools
library. This decorator will then be applied to functions whose runtime we are interested in.
Tracing Decorator: @tracefunc
The code below represents a common decorator pattern that has a reusable and flexible structure. Notice the placement of functool.wraps
. It is a decorator for our closure. This decorator preserves func
’s metadata as it is passed to the closure.
import functools
def tracefunc(func):
"""Decorates a function to show its trace."""
@functools.wraps(func)
def tracefunc_closure(*args, **kwargs):
"""The closure."""
result = func(*args, **kwargs)
print(f"{func.__name__}(args={args}, kwargs={kwargs}) => {result}")
return result
return tracefunc_closure
@tracefunc
def show_args_and_kwargs(*args, **kwargs):
return
@tracefunc
def show_args_and_kwargs2(*args, **kwargs):
return
if __name__ == "__main__":
show_args_and_kwargs(10)
show_args_and_kwargs(color="Red")
show_args_and_kwargs(10, 200, color="Blue", type="Dog")
show_args_and_kwargs2(2, 'ABCD', person={'name': 'Mark', 'phone': '78984557235', 'age': 37})
The output
show_args_and_kwargs(args=(10,), kwargs={}) => None
show_args_and_kwargs(args=(), kwargs={'color': 'Red'}) => None
show_args_and_kwargs(args=(10, 200), kwargs={'color': 'Blue', 'type': 'Dog'}) => None
show_args_and_kwargs2(args=(2, 'ABCD'), kwargs={'person': {'name': 'Mark', 'phone': '78984557235', 'age': 37}}) => None
Github: https://github.com/rondweb/python-tricks/blob/main/python_trace.ipynb
Reference: https://towardsdatascience.com/a-simple-way-to-trace-code-in-python-a15a25cbbf51