Skip to content

Reference

buzz.tools

This module supplies the core functions of the py-buzz package.

DoExceptParams dataclass

Dataclass for the do_except user supplied handling method.

Attributes:

err:           The exception instance itself
base_message:  The base message parameter that was passed to the `handle_errors()` function
final_message: The final, combined message including the base message and string formatted exception
trace:         A traceback of the exception

ExcBuilderParams dataclass

Bases: Generic[TExc]

Dataclass for the exc_builder user supplied exception constructor.

Attributes:

raise_exc_class: The exception class that should be built
message:         The message to build the exception with
raise_args:      The positional arguments that are needed to build the exception
raise_kwargs:    The keyword arguments that are needed to build the exception

check_expressions

check_expressions(
    main_message: str,
    raise_exc_class: type[Exception] = Exception,
    raise_args: Iterable[Any] | None = None,
    raise_kwargs: Mapping[str, Any] | None = None,
    exc_builder: Callable[
        [ExcBuilderParams], Exception
    ] = default_exc_builder,
)

Check a series of expressions inside of a context manager. If any fail an exception is raised that contains a main message and a description of each failing expression.

Parameters:

  • main_message (str) –

    The main failure message to include in the constructed message that is passed to the raised Exception

  • raise_exc_class (type[Exception], default: Exception ) –

    The exception type to raise with the constructed message if the expression is falsey.

               Defaults to Exception.
    
               May not be None.
    
  • raise_args (Iterable[Any] | None, default: None ) –

    Additional positional args (after the constructed message) that will passed when raising an instance of the raise_exc_class.

  • raise_kwargs (Mapping[str, Any] | None, default: None ) –

    Keyword args that will be passed when raising an instance of the raise_exc_class.

  • exc_builder (Callable[[ExcBuilderParams], Exception], default: default_exc_builder ) –

    A function that should be called to construct the raised raise_exc_class. Useful for exception classes that do not take a message as the first positional argument.

Example:

The following is an example usage::

    with check_expressions("Something wasn't right") as check:
        check(a is not None)
        check(a > b, "a must be greater than b")
        check(a != 1, "a must not equal 1")
        check(b >= 0, "b must not be negative")

This would render output like::

    Checked expressions failed: Something wasn't right:
      1: first expressoin failed
      3: a must not equal 1

default_exc_builder

default_exc_builder(params: ExcBuilderParams[TExc]) -> TExc

Build an exception instance using default behavior where message is passed as first positional argument.

Some exception types such as FastAPI's HTTPException do not take a message as the first positional argument, so they will need a different exception builder.

enforce_defined

enforce_defined(
    value: TNonNull | None,
    message: str = "Value was not defined (None)",
    raise_exc_class: type[Exception] = Exception,
    raise_args: Iterable[Any] | None = None,
    raise_kwargs: Mapping[str, Any] | None = None,
    exc_builder: Callable[
        [ExcBuilderParams], Exception
    ] = default_exc_builder,
) -> TNonNull

Assert that a value is not None. If the assertion fails, raise an exception with the supplied message.

Args:

value:            The value that is checked to be non-null
message:          The failure message to attach to the raised Exception
expr:             The value that is checked for truthiness (usually an evaluated expression)
raise_exc_class:  The exception type to raise with the constructed message if the expression is falsey.

                  Defaults to Exception.
                  May not be None.

raise_args:       Additional positional args (after the constructed message) that will passed when raising
                  an instance of the ``raise_exc_class``.
raise_kwargs:     Keyword args that will be passed when raising an instance of the ``raise_exc_class``.
exc_builder:     A function that should be called to construct the raised ``raise_exc_class``. Useful for
                 exception classes that do not take a message as the first positional argument.

get_traceback

get_traceback() -> types.TracebackType | None

Retrieves the traceback after an exception has been raised.

handle_errors

handle_errors(
    message: str,
    raise_exc_class: type[Exception] | None = Exception,
    raise_args: Iterable[Any] | None = None,
    raise_kwargs: Mapping[str, Any] | None = None,
    handle_exc_class: type[Exception]
    | Tuple[type[Exception], ...] = Exception,
    ignore_exc_class: type[Exception]
    | Tuple[type[Exception], ...]
    | None = None,
    do_finally: Callable[[], None] = noop,
    do_except: Callable[[DoExceptParams], None] = noop,
    do_else: Callable[[], None] = noop,
    exc_builder: Callable[
        [ExcBuilderParams], Exception
    ] = default_exc_builder,
) -> Iterator[None]

Provide a context manager that will intercept exceptions and repackage them with a message attached:

Parameters:

  • message (str) –

    The message to attach to the raised exception.

  • raise_exc_class (type[Exception] | None, default: Exception ) –

    The exception type to raise with the constructed message if an exception is caught in the managed context. If None is passed, no new exception will be raised and only the do_except, do_else, and do_finally functions will be called.

  • raise_args (Iterable[Any] | None, default: None ) –

    Additional positional args (after the constructed message) that will passed when raising an instance of the raise_exc_class.

  • raise_kwargs (Mapping[str, Any] | None, default: None ) –

    Keyword args that will be passed when raising an instance of the raise_exc_class.

  • handle_exc_class (type[Exception] | Tuple[type[Exception], ...], default: Exception ) –

    Limits the class of exceptions that will be intercepted Any other exception types will not be caught and re-packaged. Defaults to Exception (will handle all exceptions). May also be provided as a tuple of multiple exception types to handle.

  • ignore_exc_class (type[Exception] | Tuple[type[Exception], ...] | None, default: None ) –

    Defines an exception or set of exception types that should not be handled at all. Any matching exception types will be immediately re-raised. They will not be handled by the handle_errors context manager at all. This is useful if you want a specific variant of your handle_exc_class to not be handled by handle_errors. For example, if you want to use handle_exc_class=Exception but you do not want handle_errors to handle RuntimeError. Then, you would set ignore_exc_class=RuntimeError.

  • do_finally (Callable[[], None], default: noop ) –

    A function that should always be called at the end of the block. Should take no parameters.

  • do_except (Callable[[DoExceptParams], None], default: noop ) –

    A function that should be called only if there was an exception. Must accept one parameter that is an instance of the DoExceptParams dataclass. Note that the do_except method is passed the original exception.

  • do_else (Callable[[], None], default: noop ) –

    A function that should be called only if there were no exceptions encountered.

  • exc_builder (Callable[[ExcBuilderParams], Exception], default: default_exc_builder ) –

    A function that should be called to construct the raised raise_exc_class. Useful for exception classes that do not take a message as the first positional argument.

Example:

The following is an example usage:

    with handle_errors("It didn't work"):
        some_code_that_might_raise_an_exception()

handle_errors_async async

handle_errors_async(
    message: str,
    raise_exc_class: type[Exception] | None = Exception,
    raise_args: Iterable[Any] | None = None,
    raise_kwargs: Mapping[str, Any] | None = None,
    handle_exc_class: type[Exception]
    | Tuple[type[Exception], ...] = Exception,
    ignore_exc_class: type[Exception]
    | Tuple[type[Exception], ...]
    | None = None,
    do_finally: Callable[[], None]
    | Callable[[], Coroutine[Any, Any, None]] = noop,
    do_except: Callable[[DoExceptParams], None]
    | Callable[
        [DoExceptParams], Coroutine[Any, Any, None]
    ] = noop,
    do_else: Callable[[], None]
    | Callable[[], Coroutine[Any, Any, None]] = noop,
    exc_builder: Callable[
        [ExcBuilderParams], Exception
    ] = default_exc_builder,
) -> AsyncIterator[None]

Provide an async context manager that will intercept exceptions and repackage them with a message attached:

Parameters:

  • message (str) –

    The message to attach to the raised exception.

  • raise_exc_class (type[Exception] | None, default: Exception ) –

    The exception type to raise with the constructed message if an exception is caught in the managed context. If None is passed, no new exception will be raised and only the do_except, do_else, and do_finally functions will be called.

  • raise_args (Iterable[Any] | None, default: None ) –

    Additional positional args (after the constructed message) that will passed when raising an instance of the raise_exc_class.

  • raise_kwargs (Mapping[str, Any] | None, default: None ) –

    Keyword args that will be passed when raising an instance of the raise_exc_class.

  • handle_exc_class (type[Exception] | Tuple[type[Exception], ...], default: Exception ) –

    Limits the class of exceptions that will be intercepted Any other exception types will not be caught and re-packaged. Defaults to Exception (will handle all exceptions). May also be provided as a tuple of multiple exception types to handle.

  • ignore_exc_class (type[Exception] | Tuple[type[Exception], ...] | None, default: None ) –

    Defines an exception or set of exception types that should not be handled at all. Any matching exception types will be immediately re-raised. They will not be handled by the handle_errors context manager at all. This is useful if you want a specific variant of your handle_exc_class to not be handled by handle_errors. For example, if you want to use handle_exc_class=Exception but you do not want handle_errors to handle RuntimeError. Then, you would set ignore_exc_class=RuntimeError.

  • do_finally (Callable[[], None] | Callable[[], Coroutine[Any, Any, None]], default: noop ) –

    A function that should always be called at the end of the block. Should take no parameters. May be an async function.

  • do_except (Callable[[DoExceptParams], None] | Callable[[DoExceptParams], Coroutine[Any, Any, None]], default: noop ) –

    A function that should be called only if there was an exception. Must accept one parameter that is an instance of the DoExceptParams dataclass. May be an async function. Note that the do_except method is passed the original exception.

  • do_else (Callable[[], None] | Callable[[], Coroutine[Any, Any, None]], default: noop ) –

    A function that should be called only if there were no exceptions encountered. May be an async function.

  • exc_builder (Callable[[ExcBuilderParams], Exception], default: default_exc_builder ) –

    A function that should be called to construct the raised raise_exc_class. Useful for exception classes that do not take a message as the first positional argument.

Example:

The following is an example usage:

    async with handle_errors("It didn't work"):
        await some_code_that_might_raise_an_exception()

reformat_exception

reformat_exception(message: str, err: Exception) -> str

Reformat an exception by adding a message to it and reporting the original exception name and message.

require_condition

require_condition(
    expr: Any,
    message: str,
    raise_exc_class: type[Exception] = Exception,
    raise_args: Iterable[Any] | None = None,
    raise_kwargs: Mapping[str, Any] | None = None,
    exc_builder: Callable[
        [ExcBuilderParams], Exception
    ] = default_exc_builder,
)

Assert that an expression is truthy. If the assertion fails, raise an exception with the supplied message.

Args:

message:         The failure message to attach to the raised Exception
expr:            The value that is checked for truthiness (usually an evaluated expression)
raise_exc_class: The exception type to raise with the constructed message if the expression is falsey.
                 Defaults to Exception.
                 May not be None.
raise_args:      Additional positional args (after the constructed message) that will passed when raising
                 an instance of the ``raise_exc_class``.
raise_kwargs:    Keyword args that will be passed when raising an instance of the ``raise_exc_class``.
exc_builder:     A function that should be called to construct the raised ``raise_exc_class``. Useful for
                 exception classes that do not take a message as the first positional argument.

buzz.base

This module defines the Buzz base class.

Buzz

Bases: Exception

This provides a specialized exception class that wraps up all the buzz utility functions.

__init__
__init__(message)

Initialize the exception with a message. Dedent the supplied message.

check_expressions classmethod
check_expressions(*args, **kwargs)

Call the check_expressions() context manager with this class as the raise_exc_class kwarg.

enforce_defined classmethod
enforce_defined(
    value: TNonNull | None, *args, **kwargs
) -> TNonNull

Call the enforce_defined() function with this class as the raise_exc_class kwarg.

get_traceback classmethod
get_traceback(*args, **kwargs)

Call the get_traceback() function.

handle_errors classmethod
handle_errors(*args, re_raise=True, **kwargs)

Call the handle_errors() context manager with this class as the raise_exc_class kwarg.

Note:

If `re_raise` is not True, `None` will be passed as the `raise_exc_class` kwarg.
require_condition classmethod
require_condition(*args, **kwargs)

Call the require_condition() function with this class as the raise_exc_class kwarg.