From b926d6253c977fd2658480d22cd0acedcfc0d1d4 Mon Sep 17 00:00:00 2001 From: Azalea Gui <22280294+hykilpikonna@users.noreply.github.com> Date: Sat, 16 Nov 2024 18:52:53 -0500 Subject: [PATCH] [+] Safe function wrapper --- hypy_utils/__init__.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/hypy_utils/__init__.py b/hypy_utils/__init__.py index daba24b..0b1065e 100644 --- a/hypy_utils/__init__.py +++ b/hypy_utils/__init__.py @@ -3,12 +3,16 @@ from __future__ import annotations __version__ = "1.0.22" import time +import logging from typing import Callable from .color_utils import * from .serializer import * +log = logging.getLogger(__name__) + + class Timer: start: int @@ -39,3 +43,33 @@ def run_time(func: Callable, *args, **kwargs): _ = [func(*args, **kwargs) for _ in range(iter)] ms = (time.time_ns() - start) / 1e6 print(f'RT {name:30} {ms:6.1f} ms') + + +def safe(func: Callable, on_error: Callable[[Exception], Any] = None) -> Callable: + """ + Wrapper for safely executing a function and returning the result of on_error if an exception occurs + + If on_error is None, it will return None on error + + Example Usage: + >>> safe(lambda x: 1 / x)(0) + None + >>> safe(lambda x: 1 / x)(2) + 0.5 + + :param func: Function that needs safe execution + :param on_error: Function to execute when an error occurs + :return: Wrapped function + """ + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except Exception as e: + if on_error: + return on_error(e) + else: + log.exception(e) + return None + + return wrapper +