Create debug_tools module with error handling and timing tools.
This commit is contained in:
90
src/AuDaGe/debug_tools.py
Normal file
90
src/AuDaGe/debug_tools.py
Normal file
@@ -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
|
||||||
Reference in New Issue
Block a user