Trace Code in Python

COVID-19: Immunity and contact tracing - SciLine

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 functoolsdef 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@tracefuncdef show_args_and_kwargs(*args, **kwargs):    return@tracefuncdef show_args_and_kwargs2(*args, **kwargs):    returnif __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={}) => Noneshow_args_and_kwargs(args=(), kwargs={'color': 'Red'}) => Noneshow_args_and_kwargs(args=(10, 200), kwargs={'color': 'Blue', 'type': 'Dog'}) => Noneshow_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

Post a Comment

Previous Post Next Post