diff --git a/drresult/class_decorators.py b/drresult/class_decorators.py index f92c763..d4c5aad 100644 --- a/drresult/class_decorators.py +++ b/drresult/class_decorators.py @@ -12,6 +12,7 @@ - constructs_as_result: Wraps the construction of a class in a `Result` type. """ + def make_drresult_constructs_as_result_decorator[ T ]( @@ -27,6 +28,7 @@ def make_drresult_constructs_as_result_decorator[ Returns: Callable: A decorator for classes. """ + def make_drresult_constructs_as_result_wrapper(cls: Type[T]) -> Type[T]: Base = type(cls) # type: Any diff --git a/drresult/function_decorators.py b/drresult/function_decorators.py index 697182e..462be42 100644 --- a/drresult/function_decorators.py +++ b/drresult/function_decorators.py @@ -21,6 +21,7 @@ - not_expects_default: Default list of unexpected exceptions. """ + def noexcept[T](func: Callable[..., T]) -> Callable[..., T]: """Decorator to mark a function as not expecting any exceptions. @@ -33,6 +34,7 @@ def noexcept[T](func: Callable[..., T]) -> Callable[..., T]: Raises: Panic: If an unexpected exception occurs. """ + def wrapper(*args: Any, **kwargs: Any) -> T: try: return func(*args, **kwargs) @@ -43,6 +45,7 @@ def wrapper(*args: Any, **kwargs: Any) -> T: return wrapper + # Exception lists for internal use LanguageLevelExceptions: List[Type[BaseException]] = [ AssertionError, @@ -61,6 +64,7 @@ def wrapper(*args: Any, **kwargs: Any) -> T: expects_default: List[Type[BaseException]] = [Exception] not_expects_default: List[Type[BaseException]] = LanguageLevelExceptions + SystemLevelExceptions + def make_drresult_returns_result_decorator[ T ]( @@ -98,6 +102,7 @@ def drresult_returns_result_wrapper(*args: Any, **kwargs: Any) -> Result[T]: return make_drresult_returns_result_wrapper + def returns_result[ T ](*decorator_args: Any, **decorator_kwargs: Any) -> ( diff --git a/drresult/gather_result.py b/drresult/gather_result.py index 3381bb4..0dc11d8 100644 --- a/drresult/gather_result.py +++ b/drresult/gather_result.py @@ -14,17 +14,9 @@ - gather_result: Context manager to capture exceptions as a `Result`. """ -class ResultContainer[T]: - """Container to hold a `Result` within a context. - - Attributes: - _result (Result[T] | Result[None]): The result held. - _finalized (bool): Indicates if the result is finalized. - Methods: - set(result): Set the result. - get() -> Result[T] | Result[None]: Get the finalized result. - """ +class ResultContainer[T]: + """Container to hold a `Result` within a context.""" def __init__(self) -> None: self._result: Result[T] | Result[None] = Ok(None) @@ -54,6 +46,7 @@ def get(self) -> Result[T] | Result[None]: assert self._finalized, "Cannot get result when not finalized" return self._result + class gather_result[T]: """Context manager to capture exceptions and convert them into a `Result`. @@ -62,11 +55,6 @@ class gather_result[T]: # Code that might raise exceptions result_container.set(Ok(value)) result = result_container.get() - - Attributes: - _expects (Tuple[Type[BaseException], ...]): Expected exceptions. - _not_expects (Tuple[Type[BaseException], ...]): Unexpected exceptions. - _container (ResultContainer[T]): The result container. """ def __init__( @@ -87,16 +75,7 @@ def __enter__(self): return self._container def __exit__(self, exc_type, exc_value, traceback): - """Exit the context, handling exceptions. - - Args: - exc_type: The exception type. - exc_value: The exception instance. - traceback: The traceback object. - - Returns: - bool: True if the exception was handled, False otherwise. - """ + """Exit the context, handling exceptions.""" match exc_value: case None: pass diff --git a/drresult/logging.py b/drresult/logging.py index 0b43355..7614277 100644 --- a/drresult/logging.py +++ b/drresult/logging.py @@ -14,6 +14,7 @@ - log_panic: Context manager to log `Panic` exceptions using the provided logger. """ + @contextmanager def log_panic(logger: logging.Logger): """Context manager to log `Panic` exceptions. diff --git a/drresult/result.py b/drresult/result.py index 70236e0..3068425 100644 --- a/drresult/result.py +++ b/drresult/result.py @@ -22,12 +22,9 @@ - excepthook: Custom exception hook to print formatted exceptions. """ -class BaseResult[T]: - """Base class for `Ok` and `Err` result types. - Attributes: - _value (T): The value held by the result. - """ +class BaseResult[T]: + """Base class for `Ok` and `Err` result types.""" def __init__(self): # pragma: no cover self._value: T @@ -72,11 +69,7 @@ def _unexpected(self, msg: Optional[str] = None) -> NoReturn: class Ok[T](BaseResult[T]): - """Represents a successful result. - - Attributes: - _value (T): The successful value. - """ + """Represents a successful result.""" __match_args__ = ('value',) @@ -183,11 +176,7 @@ def unwrap_or_return(self) -> T: class Err[E: BaseException](BaseResult[E]): - """Represents an error result. - - Attributes: - _value (E): The exception representing the error. - """ + """Represents an error result.""" __match_args__ = ('error',) @@ -304,15 +293,8 @@ def unwrap_or_return(self) -> NoReturn: type Result[T] = Ok[T] | Err[BaseException] """Type alias for `Result`, which can be an `Ok` or an `Err`.""" -def filter_traceback(e: BaseException) -> List[traceback.FrameSummary]: - """Filter the traceback to exclude internal frames. - - Args: - e (BaseException): The exception to filter. - Returns: - List[traceback.FrameSummary]: The filtered traceback frames. - """ +def filter_traceback(e: BaseException) -> List[traceback.FrameSummary]: tb = traceback.extract_tb(e.__traceback__) return [ frame @@ -330,53 +312,28 @@ def filter_traceback(e: BaseException) -> List[traceback.FrameSummary]: ) ] -def format_traceback(e: BaseException) -> str: - """Format the traceback of an exception. - - Args: - e (BaseException): The exception to format. - Returns: - str: The formatted traceback string. - """ +def format_traceback(e: BaseException) -> str: new_tb_list = filter_traceback(e) trace_to_print = ''.join(traceback.format_list(new_tb_list)) return trace_to_print -def format_exception(e: BaseException) -> str: - """Format the exception message. - - Args: - e (BaseException): The exception to format. - Returns: - str: The exception message. - """ +def format_exception(e: BaseException) -> str: return ''.join(traceback.format_exception_only(e))[:-1] -def format_traceback_exception(e: BaseException) -> str: - """Format the full traceback and exception message. - - Args: - e (BaseException): The exception to format. - Returns: - str: The formatted traceback and exception message. - """ +def format_traceback_exception(e: BaseException) -> str: return f'{format_traceback(e)}{format_exception(e)}' -def excepthook(type, e, traceback): - """Custom exception hook to print formatted exceptions. - Args: - type: The exception type. - e (BaseException): The exception instance. - traceback: The traceback object. - """ +def excepthook(type, e, traceback): print(f'{format_traceback_exception(e)}') + sys.excepthook = excepthook + class Panic(Exception): """Exception raised for unexpected errors leading to program termination.