Skip to content

Commit

Permalink
Cleanup documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
olekli committed Oct 17, 2024
1 parent cd8a84e commit 5381663
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 79 deletions.
2 changes: 2 additions & 0 deletions drresult/class_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
](
Expand All @@ -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

Expand Down
5 changes: 5 additions & 0 deletions drresult/function_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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)
Expand All @@ -43,6 +45,7 @@ def wrapper(*args: Any, **kwargs: Any) -> T:

return wrapper


# Exception lists for internal use
LanguageLevelExceptions: List[Type[BaseException]] = [
AssertionError,
Expand All @@ -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
](
Expand Down Expand Up @@ -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) -> (
Expand Down
29 changes: 4 additions & 25 deletions drresult/gather_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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`.
Expand All @@ -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__(
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions drresult/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
65 changes: 11 additions & 54 deletions drresult/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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',)

Expand Down Expand Up @@ -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',)

Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down

0 comments on commit 5381663

Please sign in to comment.