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 `jandle_errors()` function
final_message: The final, combined message including the base message and string formatted exception
trace: A traceback of the exception
ExcBuilderParams
dataclass
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
base_message: An optional "base" message. This will carry the original message from:
- handle_errors
- check_expressions
check_expressions
check_expressions(
base_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,
do_except: Callable[[Exception], None] | None = None,
do_else: Callable[[], None] | None = None,
)
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:
-
base_message
(str
) –The base failure message to include in the constructed message that is passed to the raised Exception. Will be included in
ExcBuilderParams
passed toexc_builder
. -
raise_exc_class
(type[Exception]
, default:Exception
) –The exception type to raise with the assembled message if any of the expressions are falsey.
Defaults to Exception. May not be None.
-
raise_args
(Iterable[Any] | None
, default:None
) –Additional positional args (after the assembled 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. -
do_except
(Callable[[Exception], None] | None
, default:None
) –A function that should be called only if the any of the expressions are falsey. Must accept one parameter that is the exception that will be raised. If not provided, nothing will be done.
-
do_else
(Callable[[], None] | None
, default:None
) –A function that should be called if none of the the expressions are falsey. If not provided, nothing will be done.
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) -> Exception
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,
do_except: Callable[[Exception], None] | None = None,
do_else: Callable[[], None] | None = None,
) -> 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
raise_exc_class: The exception type to raise with the constructed message if the expression is None.
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.
do_except: A function that should be called only if value is not defined.
Must accept one parameter that is the exception that will be raised.
If not provided, nothing will be done.
do_else: A function that should be called if the value is defined.
If not provided, nothing will be done.
ensure_type
ensure_type(
value: Any,
type_: type[EnsuredType],
message: str | None = 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,
do_except: Callable[[Exception], None] | None = None,
do_else: Callable[[], None] | None = None,
) -> EnsuredType
Assert that a value is of a specific type. If the assertion fails, raise an exception with the supplied message.
Args:
value: The value that is to be checked
type_: The type that the value must be of
message: The failure message to attach to the raised Exception
raise_exc_class: The exception type to raise with the constructed message if the type does not match
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.
do_except: A function that should be called only if value is of the wrong type.
Must accept one parameter that is the exception that will be raised.
If not provided, nothing will be done.
do_else: A function that should be called if the value is of the wrong type.
If not provided, nothing will be done.
get_traceback
get_traceback() -> types.TracebackType | None
Retrieves the traceback after an exception has been raised.
handle_errors
handle_errors(
base_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] | None = None,
do_except: Callable[[DoExceptParams], None]
| None = None,
do_else: Callable[[], None] | None = None,
exc_builder: Callable[
[ExcBuilderParams], Exception
] = default_exc_builder,
) -> Iterator[None]
Provide a context manager that will intercept exceptions and repackage them in a new exception with a message attached that combines the base message along with the message from the handled exception:
Parameters:
-
base_message
(str
) –The base message to attach to the raised exception. Will be included in
ExcBuilderParams
passed toexc_builder
. -
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 thedo_except
,do_else
, anddo_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 yourhandle_exc_class
to not be handled byhandle_errors
. For example, if you want to usehandle_exc_class=Exception
but you do not wanthandle_errors
to handleRuntimeError
. Then, you would setignore_exc_class=RuntimeError
. -
do_finally
(Callable[[], None] | None
, default:None
) –A function that should always be called at the end of the block. Should take no parameters. If not provided, nothing will be done.
-
do_except
(Callable[[DoExceptParams], None] | None
, default: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 thedo_except
method is passed the original exception. If not provided, nothing will be done. -
do_else
(Callable[[], None] | None
, default:None
) –A function that should be called only if there were no exceptions encountered. If not provided, nothing will be done.
-
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(
base_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]]
| None = None,
do_except: Callable[[DoExceptParams], None]
| Callable[[DoExceptParams], Coroutine[Any, Any, None]]
| None = None,
do_else: Callable[[], None]
| Callable[[], Coroutine[Any, Any, None]]
| None = None,
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:
-
base_message
(str
) –The base message to attach to the raised exception. Will be included in
ExcBuilderParams
passed toexc_builder
. -
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 thedo_except
,do_else
, anddo_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 yourhandle_exc_class
to not be handled byhandle_errors
. For example, if you want to usehandle_exc_class=Exception
but you do not wanthandle_errors
to handleRuntimeError
. Then, you would setignore_exc_class=RuntimeError
. -
do_finally
(Callable[[], None] | Callable[[], Coroutine[Any, Any, None]] | None
, default:None
) –A function that should always be called at the end of the block. Should take no parameters. May be an async function. If not provided, nothing will be done.
-
do_except
(Callable[[DoExceptParams], None] | Callable[[DoExceptParams], Coroutine[Any, Any, None]] | None
, default: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. May be an async function. Note that thedo_except
method is passed the original exception. If not provided, nothing will be done. -
do_else
(Callable[[], None] | Callable[[], Coroutine[Any, Any, None]] | None
, default:None
) –A function that should be called only if there were no exceptions encountered. May be an async function. If not provided, nothing will be done.
-
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,
do_except: Callable[[Exception], None] | None = None,
do_else: Callable[[], None] | None = None,
)
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.
do_except: A function that should be called only if the condition fails.
Must accept one parameter that is the exception that will be raised.
If not provided, nothing will be done.
do_else: A function that should be called if the condition passes.
If not provided, nothing will be done.
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: str,
*args: Any,
base_message: str | None = None,
**kwargs: Any,
)
Initialize the exception with a message.
Also, dedent the supplied message.
check_expressions
classmethod
check_expressions(
base_message: str,
raise_args: Iterable[Any] | None = None,
raise_kwargs: Mapping[str, Any] | None = None,
do_except: Callable[[Exception], None] | None = None,
do_else: Callable[[], None] | None = None,
)
Check a series of expressions inside of a context manager. If any fail an exception (instance of this class) is raised that contains a main message and a description of each failing expression.
Parameters:
-
base_message
(str
) –The base failure message to include in the constructed message that is passed to the raised Exception. Will be included in
ExcBuilderParams
passed toexc_builder
. -
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
. -
do_except
(Callable[[Exception], None] | None
, default:None
) –A function that should be called only if the any of the expressions are falsey. Must accept one parameter that is the exception that will be raised. If not provided, nothing will be done.
-
do_else
(Callable[[], None] | None
, default:None
) –A function that should be called if none of the the expressions are falsey. If not provided, nothing will be done.
Example:
The following is an example usage::
with Buzz.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
enforce_defined
classmethod
enforce_defined(
value: TNonNull | None,
message: str = "Value was not defined (None)",
raise_args: Iterable[Any] | None = None,
raise_kwargs: Mapping[str, Any] | None = None,
do_except: Callable[[Exception], None] | None = None,
do_else: Callable[[], None] | None = None,
) -> TNonNull
Assert that a value is not None. If the assertion fails, raise an exception (instance of this class) 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_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`.
do_except: A function that should be called only if value is not defined.
Must accept one parameter that is the exception that will be raised.
If not provided, nothing will be done.
do_else: A function that should be called if the value is defined.
If not provided, nothing will be done.
ensure_type
classmethod
ensure_type(
value: Any,
type_: type[EnsuredType],
message: str = "Value was not of type {type_}",
raise_args: Iterable[Any] | None = None,
raise_kwargs: Mapping[str, Any] | None = None,
do_except: Callable[[Exception], None] | None = None,
do_else: Callable[[], None] | None = None,
) -> EnsuredType
Assert that a value is of a specific type. If the assertion fails, raise an exception (instance of this class) with the supplied message.
Args:
value: The value that is to be checked
type_: The type that the value must be of
message: The failure message to attach to the raised Exception
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`.
do_except: A function that should be called only if value is of the wrong type.
Must accept one parameter that is the exception that will be raised.
If not provided, nothing will be done.
do_else: A function that should be called if the value is of the wrong type.
If not provided, nothing will be done.
exc_builder
classmethod
exc_builder(params: ExcBuilderParams) -> Self
Build an instance of this Buzz exception.
This method is used by the other methods to construct the exception. Binds attributes from ExcBuilderParams including the base_message.
get_traceback
classmethod
get_traceback(*args: Any, **kwargs: Any)
Call the get_traceback()
function.
handle_errors
classmethod
handle_errors(
base_message: str,
re_raise: bool = True,
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] | None = None,
do_except: Callable[[DoExceptParams], None]
| None = None,
do_else: Callable[[], None] | None = None,
)
Provide a context manager that will intercept exceptions and repackage them in a new exception (instance of this class) with a message attached that combines the base message along with the message from the handled exception:
Parameters:
-
base_message
(str
) –The base message to attach to the raised exception. Will be included in
ExcBuilderParams
passed toexc_builder
. -
re_raise
(bool
, default:True
) –If True (the default), then a exception (instance of this class) will be raised after handling any caught exceptoins. If False, no exception will be raised after handling any exceptions. This will effectively swallow the expression. Note that the
do_
methods will still be executed. -
raise_exc_class
–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 thedo_except
,do_else
, anddo_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 yourhandle_exc_class
to not be handled byhandle_errors
. For example, if you want to usehandle_exc_class=Exception
but you do not wanthandle_errors
to handleRuntimeError
. Then, you would setignore_exc_class=RuntimeError
. -
do_finally
(Callable[[], None] | None
, default:None
) –A function that should always be called at the end of the block. Should take no parameters. If not provided, nothing will be done.
-
do_except
(Callable[[DoExceptParams], None] | None
, default: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 thedo_except
method is passed the original exception. If not provided, nothing will be done. -
do_else
(Callable[[], None] | None
, default:None
) –A function that should be called only if there were no exceptions encountered. If not provided, nothing will be done.
Example:
The following is an example usage:
with Buzz.handle_errors("It didn't work"):
some_code_that_might_raise_an_exception()
require_condition
classmethod
require_condition(
expr: Any,
message: str,
raise_args: Iterable[Any] | None = None,
raise_kwargs: Mapping[str, Any] | None = None,
do_except: Callable[[Exception], None] | None = None,
do_else: Callable[[], None] | None = None,
)
Assert that an expression is truty. If the assertion fails, raise an exception (instance of this class) 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_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`.
do_except: A function that should be called only if the condition fails.
Must accept one parameter that is the exception that will be raised.
If not provided, nothing will be done.
do_else: A function that should be called if the condition passes.
If not provided, nothing will be done.