add result pattern including relevant test cases

This commit was merged in pull request #3.
This commit is contained in:
2025-10-23 09:20:24 +02:00
parent a6ffc2ebf4
commit 8fdfbebb75
2 changed files with 286 additions and 6 deletions

View File

@@ -1,16 +1,21 @@
from __future__ import annotations
import dataclasses as dc
import inspect
import typing as t
from collections.abc import Callable
from functools import wraps
from logging import Logger
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from logging import Logger
P = t.ParamSpec("P")
T = t.TypeVar("T")
# ** Exceptions for result wrappers
class WAccessResultDespiteError(Exception):
class WrapperAccessResultDespiteError(Exception):
"""wrapped results exception: raised if result is accessed, even though
there was an error in the underlying procedure"""
@@ -24,6 +29,8 @@ class Status:
class StatusHandler:
__slots__ = ("logger", "_SUCCESS")
def __init__(
self,
logger: Logger | None = None,
@@ -120,15 +127,18 @@ STATUS_HANDLER: t.Final[StatusHandler] = StatusHandler()
class ResultWrapper(t.Generic[T]):
__slots__ = ("_result", "status")
def __init__(
self,
result: T | NotSet,
exception: Exception | None,
code_on_error: int,
) -> None:
assert (isinstance(result, NotSet) and exception is not None) or (
not isinstance(result, NotSet) and exception is None
), "set >NotSet< without exception or result with exception"
if isinstance(result, NotSet) and exception is None:
raise ValueError("[ResultWrapper] Set >NotSet< without exception")
elif not isinstance(result, NotSet) and exception is not None:
raise ValueError("[ResultWrapper] Set result with exception")
self._result = result
status: Status = STATUS_HANDLER.SUCCESS
@@ -139,7 +149,9 @@ class ResultWrapper(t.Generic[T]):
@property
def result(self) -> T:
if isinstance(self._result, NotSet):
raise WAccessResultDespiteError("Can not access result because it is not set")
raise WrapperAccessResultDespiteError(
"Can not access result because it is not set"
)
return self._result
def __str__(self) -> str: