Page MenuHomec4science

debug.py
No OneTemporary

File Metadata

Created
Sun, Sep 1, 15:18

debug.py

'''
Debug module
'''
from functools import wraps, partial
import cProfile
import pstats
import time
def debug(func=None, *, prof=False, timer=False, sign=False):
'''
Debug decorator
'''
if func is None:
return partial(debug, prof=prof, timer=timer, sign=sign)
@wraps(func)
def wrapper_debug(*args, **kwargs):
if prof:
"""Print the profile of the decorated function"""
with cProfile.Profile() as _prof:
value = func(*args, **kwargs)
stats = pstats.Stats(_prof)
stats.sort_stats(pstats.SortKey.TIME)
""" print 1% of calls """
stats.print_stats(0.01)
elif timer:
"""Print the runtime of the decorated function"""
start_time = time.perf_counter()
value = func(*args, **kwargs)
end_time = time.perf_counter()
run_time = end_time - start_time
print(f"Finished {func.__name__!r} in {run_time:.4f} secs")
elif sign:
"""Print the function signature and return value"""
args_repr = [repr(a) for a in args]
kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()]
signature = ", ".join(args_repr + kwargs_repr)
print(f"Calling {func.__name__}({signature})")
value = func(*args, **kwargs)
print(f"{func.__name__!r} returned {value!r}")
else:
return func(*args, **kwargs)
return value
return wrapper_debug

Event Timeline