From bd254fe3e5aa21baf6e9f93456bc64e97005f653 Mon Sep 17 00:00:00 2001 From: Silcantar <1491897+Silcantar@users.noreply.github.com> Date: Fri, 2 Oct 2026 16:33:29 -0500 Subject: [PATCH] Create debug_tools module with error handling and timing tools. --- src/AuDaGe/debug_tools.py | 90 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 src/AuDaGe/debug_tools.py diff --git a/src/AuDaGe/debug_tools.py b/src/AuDaGe/debug_tools.py new file mode 100644 index 0000000..85a2d55 --- /dev/null +++ b/src/AuDaGe/debug_tools.py @@ -0,0 +1,90 @@ +""" +AuDaGe debugging tools + +name: debug_tools.py +by: Josh Lucas +date: 2026-10-02 + +desc: Debugging tools for AuDaGe. +""" + +import time +from collections.abc import Callable +from enum import IntEnum + + +def print_and_return(value: any) -> any: + print(value) + return value + + +def catch( + exception: Exception, + func: Callable, + *args, + handle: Callable = lambda e: e, + **kwargs, +) -> any: + """Function for catching errors in-line. + + Parameters + ---------- + exception : Exception + The exception to catch. + func : Callable + Function or lambda to catch exceptions from. + *args + Positional arguments for `func`. + handle : Callable + Code to execute when an exception is caught. + **kwargs + Keyword arguments for `func`. + + Returns + ------- + any + The return value of `func` if no exception is caught; else the return + value of `handle`. + """ + try: + return func(*args, **kwargs) + except exception as e: + return handle(e) + + +class TimeUnit(IntEnum): + """Conversion ratios to/from nanoseconds for various time units.""" + + NS = 1e9 + US = 1e6 + MS = 1e3 + S = 1 + + +class MeasureTime: + """Context manager for measuring the execution time of a block of code.""" + + def __init__( + self, + unit: TimeUnit = TimeUnit.S, + do_print: bool = False, + message: str = "Time: {time:.3f} {unit}", + timer: Callable = time.perf_counter, + ): + self.unit = unit + self.do_print = do_print + self.message = message + self.timer = timer + + def __enter__(self): + self.start = self.timer() + return self + + def __exit__(self, type, value, traceback): + self.time = (self.timer() - self.start) * self.unit + self.readout = self.message.format( + time=self.time, unit=self.unit.name.lower() + ) + if self.do_print: + print(self.readout) + # return True