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:

Name Type Description
err Exception

The exception instance itself

base_message str

The base message parameter that was passed to the handle_errors() function

final_message str

The final, combined message including the base message and string formatted exception

trace types.TracebackType | None

A traceback of the exception

ExcBuilderParams dataclass

Bases: Generic[TExc]

Dataclass for the exc_builder user supplied exception constructor.

Attributes:

Name Type Description
raise_exc_class Type[TExc]

The exception class that should be built

message str

The message to build the exception with

raise_args Iterable[Any]

The positional arguments that are needed to build the exception

raise_kwargs Mapping[str, Any]

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:

Name Type Description Default
main message

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

required
raise_exc_class type[Exception]

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

           Defaults to Exception.

           May not be None.
Exception
raise_args Iterable[Any] | None

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

None
raise_kwargs Mapping[str, Any] | None

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

None
exc_builder Callable[[ExcBuilderParams], Exception]

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.

default_exc_builder
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.

Parameters:

Name Type Description Default
value TNonNull | None

The value that is checked to be non-null

required
message str

The failure message to attach to the raised Exception

'Value was not defined (None)'
expr

The value that is checked for truthiness (usually an evaluated expression)

required
raise_exc_class type[Exception]

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

          Defaults to Exception.
          May not be None.
Exception
raise_args Iterable[Any] | None

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

None
raise_kwargs Mapping[str, Any] | None

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

None
exc_builder Callable[[ExcBuilderParams], Exception]

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.

default_exc_builder

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:

Name Type Description Default
message str

The message to attach to the raised exception.

required
raise_exc_class type[Exception] | None

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.

Exception
raise_args Iterable[Any] | None

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

None
raise_kwargs Mapping[str, Any] | None

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

None
handle_exc_class type[Exception] | Tuple[type[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.

Exception
ignore_exc_class type[Exception] | Tuple[type[Exception], ...] | 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.

None
do_finally Callable[[], None]

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

noop
do_except Callable[[DoExceptParams], None]

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.

noop
do_else Callable[[], None]

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

noop
exc_builder Callable[[ExcBuilderParams], Exception]

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.

default_exc_builder
Example

The following is an example usage:

with handle_errors("It didn't work"):
    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.

Parameters:

Name Type Description Default
message str

The failure message to attach to the raised Exception

required
expr Any

The value that is checked for truthiness (usually an evaluated expression)

required
raise_exc_class type[Exception]

The exception type to raise with the constructed message if the expression is falsey. Defaults to Exception. May not be None.

Exception
raise_args Iterable[Any] | None

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

None
raise_kwargs Mapping[str, Any] | None

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

None
exc_builder Callable[[ExcBuilderParams], Exception]

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.

default_exc_builder

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: TNonNull | None, **kwargs: TNonNull | None) -> 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.