[+] Safe function wrapper

This commit is contained in:
2024-11-16 18:52:53 -05:00
parent b9ed726caa
commit b926d6253c
+34
View File
@@ -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