### Install py-buzz with demo extra using pip Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/demo.md This command installs the `py-buzz` package along with its 'demo' extra, which includes additional features and examples for demonstration purposes. ```bash pip install py-buzz[demo] ``` -------------------------------- ### Install py-buzz via pip Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/index.md Instructions to install the latest release of the py-buzz library from PyPI using pip, the Python package installer. ```Bash pip install py-buzz ``` -------------------------------- ### Install and Run py-buzz Demos with pip Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/index.md Commands to install the optional demo extra for py-buzz and then execute the demo application using pip. ```Bash pip install py-buzz[demo] py-buzz-demo ``` -------------------------------- ### Install and Run py-buzz Demos with uvx Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/index.md Alternative commands to install the optional demo extra for py-buzz and run the demo application using `uvx`. ```Bash uvx --from=py-buzz[demo] py-buzz-demo ``` -------------------------------- ### Basic Usage of require_condition Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/index.md An example demonstrating how to import and use the `require_condition` function from the `buzz` module to enforce a condition and raise an exception if it fails. ```Python from buzz import require_condition require_condition(check_something(), "The check failed!") ``` -------------------------------- ### Output of reformat_exception Example Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Displays the console output generated when `reformat_exception()` is used to prepend a custom message to an existing exception's details. ```text > welp...that didn't work -- ValueError: I didn't like that ``` -------------------------------- ### Custom Exception Construction with `exc_builder` Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Explains how to use the `exc_builder` parameter to provide a custom function for constructing exceptions, especially useful for non-standard exception types that don't take a string message as their first argument. Includes an example with a custom error class and a builder function. ```python class WeirdArgsError(Exception): def __init__(self, *args, detail: str = "", **kwargs): self.detail = detail super().__init__(*args, **kwargs) def weird_builder(params): return exc_class(*params.raise_args, detail=params.message, **params.raise_kwargs) require_condition( some_condition(), "some_condition failed", raise_exc_class=WeirdArgsError, raise_args=["jawa"], raise_kwargs=dict("ewok"="hutt") exc_builder=weird_builder, ) ``` -------------------------------- ### Example Output of check_expressions Failure Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Illustrates the format of the exception message raised by `check_expressions()` when one or more conditions within its block evaluate to false. ```text Exception: Checked expressions failed: there will be errors 2: 2nd expression failed 3: one is not two 5: zero is still zero ``` -------------------------------- ### Display py-buzz demo help options Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/demo.md Shows all available command-line options and arguments for the `py-buzz-demo` entrypoint, providing guidance on its usage. ```bash py-buzz-demo --help ``` -------------------------------- ### Run py-buzz demo entrypoint Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/demo.md Executes the `py-buzz` demo. If no arguments are provided, all available demos will run. Specific features can be targeted using the `--feature` option. ```bash py-buzz-demo ``` -------------------------------- ### Run py-buzz demo in isolated environment with uvx Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/demo.md Executes the `py-buzz` demo in an isolated environment using `uvx`, ensuring its dependencies do not interfere with the system Python or activated virtual environments. ```bash uvx --from=py-buzz[demo] py-buzz-demo ``` -------------------------------- ### Basic exception handling with vanilla Python Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Illustrates a standard Python `try-except` block used to catch and re-package exceptions. This serves as a comparison point for the `py-buzz` `handle_errors()` context manager. ```python # Vanilla python try: this_could_fail() this_could_also_fail() this_will_definitely_fail() except Exception as err: raise RuntimeError(f"Something didn't work -- Error: {err}") ``` -------------------------------- ### APIDOC: check_expressions Context Manager Parameters Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Documents the optional keyword arguments accepted by the `check_expressions()` context manager, noting their functional similarity to parameters found in `require_condition()`. ```APIDOC check_expressions(main_message: str, ...) Parameters: main_message (str): A primary message for the exception if failures occur. raise_exc_class: Functions the same as `require_condition()`. raise_args: Functions the same as `require_condition()`. raise_kwargs: Functions the same as `require_condition()`. exc_builder: Functions the same as `require_condition()`. do_except: Functions the same as `require_condition()`. do_else: Functions the same as `require_condition()`. ``` -------------------------------- ### py-buzz handle_errors Context Manager API Reference Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Detailed API documentation for the `handle_errors` context manager, outlining its parameters and their functionalities for advanced exception handling within Python applications. ```APIDOC handle_errors(message: str, raise_exc_class: Type[Exception] = None, raise_args: Tuple = (), raise_kwargs: Dict = None, exc_builder: Callable = None, handle_exc_class: Type[Exception] = Exception, ignore_exc_class: Type[Exception] = None, do_except: Callable[[DoExceptParams], None] = None, do_else: Callable[[], None] = None, do_finally: Callable[[], None] = None) Parameters: message: str The base message to associate with the error. raise_exc_class: Type[Exception] | None The exception class to raise if an error occurs. If `None`, no new exception is raised, and the context absorbs the exception after `do_except`, `do_else`, and `do_finally` are processed. The context exits immediately after the first raised exception. raise_args: Tuple Arguments for the exception class specified by `raise_exc_class`. Functions the same as for `require_condition()`. raise_kwargs: Dict Keyword arguments for the exception class specified by `raise_exc_class`. Functions the same as for `require_condition()`. exc_builder: Callable A callable for custom exception building logic. Functions the same as for `require_condition()`. handle_exc_class: Type[Exception] Defines the type of exception (or its derived classes) that `handle_errors` will catch. Exceptions outside this inheritance tree will not be handled. `do_except` is not executed for unhandled types, but `do_else` and `do_finally` still run. ignore_exc_class: Type[Exception] | None Specifies an exception type (or its derived classes) that should *not* be handled by the context manager. Instances of this class will be immediately re-raised, bypassing `handle_errors` processing. Useful for excluding specific variants from `handle_exc_class`. do_except: Callable[[DoExceptParams], None] | None A callable function executed when an exception is caught. It accepts a `DoExceptParams` object (from `buzz`) with attributes: `err` (the caught exception), `base_message` (initial message to `handle_errors`), `final_message` (formatted error message), and `trace` (stack trace). do_else: Callable[[], None] | None A callable function that takes no arguments, executed only if no exceptions are encountered within the context. do_finally: Callable[[], None] | None A callable function that takes no arguments, executed at the end of the context regardless of whether an exception occurred, useful for cleanup. DoExceptParams (dataclass from 'buzz'): err: Exception The caught exception itself. base_message: str The message provided as the first argument to `handle_errors()`. final_message: str A formatted message describing the error. trace: List[str] A list of strings representing the stack trace. ``` -------------------------------- ### Basic Usage of py-buzz handle_errors Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Demonstrates the fundamental use of the `handle_errors` context manager to wrap code that might fail, simplifying error handling by catching exceptions and optionally raising a new class. ```python with handle_errors("Something didn't work", raise_exc_class=RuntimeError): this_could_fail() this_could_also_fail() this_will_definitely_fail() ``` -------------------------------- ### Enforce value definition with py-buzz vs. vanilla Python Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Compares traditional Python exception handling for undefined values with the concise approach offered by the `py-buzz` `enforce_defined()` function. It highlights how `py-buzz` can simplify code and assist static type checkers. ```python # Vanilla python def vanilla(val: str | None) -> str: if val is None: raise Exception("Received an undefined value!") return val.upper() # With py-buzz def buzzy(val: str | None) -> str: return enforce_defined(val).upper() ``` -------------------------------- ### API Documentation for `py-buzz.require_condition()` Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Detailed API documentation for the `require_condition()` function, including its purpose and all special keyword arguments: `raise_exc_class`, `raise_args`, `raise_kwargs`, `exc_builder`, `do_except`, and `do_else`. ```APIDOC require_condition(condition: bool, message: str, raise_exc_class: Type[Exception] = Exception, raise_args: list = None, raise_kwargs: dict = None, exc_builder: Callable[[ExcBuilderParams], Exception] = None, do_except: Callable[[Exception], None] = None, do_else: Callable[[], None] = None) Checks a condition and raises an exception if it fails. Parameters: condition: The boolean condition to check. message: The message for the exception if the condition fails. raise_exc_class: (Optional) The type of exception to raise. Defaults to Exception. raise_args: (Optional) Positional arguments to pass to the raised exception's constructor after the message. raise_kwargs: (Optional) Keyword arguments to pass to the raised exception's constructor. exc_builder: (Optional) A callable function to construct the exception. Accepts ExcBuilderParams. do_except: (Optional) A callable function to execute if the condition fails. Accepts the exception object. do_else: (Optional) A callable function to execute if the condition passes. Takes no arguments. ``` -------------------------------- ### Executing Cleanup Logic with do_finally Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Illustrates how the `do_finally` parameter can be used to define a callable function that executes at the end of the context block, regardless of whether an exception occurred, ensuring resources are properly cleaned up. ```python def close_resource(): resource.close() with handle_errors("Something went wrong", do_finally=close_resource): some_dangerous_function_that_uses_resource(resource) ``` -------------------------------- ### APIDOC: get_traceback Function Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Documents the `get_traceback` function, a utility to fetch the traceback for the current function from `sys.exc_info`. ```APIDOC get_traceback() -> traceback_object Returns: The traceback object for the current function. ``` -------------------------------- ### API documentation for enforce_defined() function parameters Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Details the various keyword arguments accepted by the `enforce_defined()` function, including `raise_exc_class`, `raise_args`, `raise_kwargs`, `exc_builder`, `do_except`, and `do_else`, noting their similarity to `require_condition()`. ```APIDOC enforce_defined(value, message=None, raise_exc_class=None, raise_args=None, raise_kwargs=None, exc_builder=None, do_except=None, do_else=None) value: The value to check for definition. message: Optional custom message for the exception. raise_exc_class: Custom exception class to raise (functions like require_condition()). raise_args: Positional arguments for the custom exception (functions like require_condition()). raise_kwargs: Keyword arguments for the custom exception (functions like require_condition()). exc_builder: Callable to build the exception (functions like require_condition()). do_except: Callable to execute if an exception is raised (functions like require_condition()). do_else: Callable to execute if no exception is raised (functions like require_condition()). ``` -------------------------------- ### Compare Python `if-raise` with `py-buzz` `require_condition()` Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Demonstrates the basic usage of `py-buzz`'s `require_condition()` function as a more concise and readable alternative to traditional Python `if-raise` statements for checking conditions and raising exceptions. ```python # Vanilla python if not some_condition(): raise Exception("some_condition failed") # With py-buzz require_condition(some_condition(), "some_condition failed") ``` -------------------------------- ### Pass Keyword Arguments to Exception with `raise_kwargs` Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Demonstrates using the `raise_kwargs` parameter to pass a dictionary of keyword arguments to the custom exception's constructor. Includes a custom exception class definition with keyword arguments to show how they are received. ```python class MyProjectError(Exception): def __init__(self, message, init_kwarg1: str | None = None, init_kwarg2: str | None = None): self.init_kwarg1 = init_kwarg1 self.init_kwarg2 = init_kwarg2 require_condition( some_condition(), "some_condition failed", raise_exc_class=MyProjectError, raise_kwargs=dict("foo", "bar"), ) ``` -------------------------------- ### API documentation for ensure_type() function parameters Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Details the various keyword arguments accepted by the `ensure_type()` function, including `raise_exc_class`, `raise_args`, `raise_kwargs`, `exc_builder`, `do_except`, and `do_else`, noting their similarity to `require_condition()`. ```APIDOC ensure_type(value, expected_type, message=None, raise_exc_class=None, raise_args=None, raise_kwargs=None, exc_builder=None, do_except=None, do_else=None) value: The value to check. expected_type: The type to enforce. message: Optional custom message for the exception. raise_exc_class: Custom exception class to raise (functions like require_condition()). raise_args: Positional arguments for the custom exception (functions like require_condition()). raise_kwargs: Keyword arguments for the custom exception (functions like require_condition()). exc_builder: Callable to build the exception (functions like require_condition()). do_except: Callable to execute if an exception is raised (functions like require_condition()). do_else: Callable to execute if no exception is raised (functions like require_condition()). ``` -------------------------------- ### Execute Action on Condition Failure with `do_except` Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Demonstrates how to use the `do_except` parameter to specify a callable function that will be executed if the condition fails, allowing for side effects like logging the error before the exception is raised. ```python def log_error(exc: Exception): logger.error(f"The condition failed: {exc}") require_condition( some_condition(), "some_condition failed", do_except=log_error, ) ``` -------------------------------- ### Pass Positional Arguments to Exception with `raise_args` Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Illustrates how to use the `raise_args` parameter to pass a list of positional arguments to the constructor of the custom exception class when the condition fails. Includes a custom exception class definition to demonstrate argument reception. ```python class MyProjectError(Exception): def __init__(self, message, init_arg1: str, init_arg2: str): self.init_arg1 = init_arg1 self.init_arg2 = init_arg2 require_condition( some_condition(), "some_condition failed", raise_exc_class=MyProjectError, raise_args=["foo", "bar"], ) ``` -------------------------------- ### Execute Action on Condition Success with `do_else` Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Shows how to use the `do_else` parameter to specify a callable function that will be executed if the condition passes, useful for actions like logging success or performing other operations when no exception is raised. ```python def log_yay(): logger.info("it's all good!") require_condition( some_condition(), "some_condition failed", do_else=log_yay, ) ``` -------------------------------- ### Customize exception details for undefined values with py-buzz Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Demonstrates how to use `enforce_defined()` to raise custom exception classes with specific positional and keyword arguments when a value is undefined, providing more contextual error information. ```python def neopolitan(val: str | None): return enforce_defined( val, "Received an undefined value!" raise_exc_class=MyProjectError, raise_args=["jawa", "ewok"], raise_kwargs=dict(hutt="pyke"), ) ``` -------------------------------- ### Handling Specific Exception Types with handle_exc_class Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Illustrates how to use the `handle_exc_class` parameter to catch and process only a specific type of exception or its subclasses, allowing other exceptions to propagate unhandled. ```python with handle_errors("Something went wrong", handle_exc_class=MyProjectError): some_function_that_could_raise_mine_or_other_errors() ``` -------------------------------- ### Using check_expressions Context Manager for Multiple Assertions Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Demonstrates how to use the `check_expressions()` context manager to validate multiple conditions within a block. If any expression fails, an exception is raised at the end, reporting all failures. No exception is raised if all expressions pass. ```python with check_expressions(main_message='there will be errors') as check: check(True) check(False) check(1 == 2, "one is not two") check('cooooooool', 'not a problem') check(0, "zero is still zero") ``` -------------------------------- ### Wrapping Exceptions with reformat_exception Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Shows how to use the `reformat_exception()` function to wrap an existing exception's message with a more informative custom message, useful for enhancing error clarity. ```python try: raise ValueError("I didn't like that") except Exception as err: print(reformat_exception("welp...that didn't work", err)) ``` -------------------------------- ### APIDOC: Buzz Base Exception Class Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Documents the `Buzz` base exception class, which provides access to various `py-buzz` error handling methods when inherited or used directly. ```APIDOC class Buzz(Exception): # Inherits standard Exception behavior # Provides class-level access to the following methods: require_condition(condition: bool, message: str, ...) enforce_defined(value: Any, message: str, ...) ensure_type(value: Any, expected_type: Type, message: str, ...) handle_errors(message: str, ...) check_expressions(main_message: str, ...) ``` -------------------------------- ### Extending Buzz Base Class for Custom Project Errors Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Illustrates how to inherit from the `Buzz` base exception class to create custom project-specific error types. This allows custom exceptions to leverage all the functionalities provided by `py-buzz`, such as `require_condition`. ```python from buzz import Buzz class MyProjectError(Buzz): pass MyProjectError.require_condition(check_vals(), "Value check failed!") ``` -------------------------------- ### APIDOC: reformat_exception Function Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Documents the `reformat_exception` function, which allows wrapping an exception message with additional context. ```APIDOC reformat_exception(message: str, original_exception: Exception) -> str message: The custom message to prepend. original_exception: The exception object whose message will be reformatted. Returns: A string combining the custom message and the original exception's details. ``` -------------------------------- ### Enforce type with py-buzz vs. vanilla Python Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Compares traditional Python type checking with the `py-buzz` `ensure_type()` function. It illustrates how `ensure_type()` simplifies type validation, raises errors for mismatches, and narrows types for static analysis. ```python # Vanilla python def vanilla(val: str | int) -> str: if not isinstance(val, str): raise Exception("Received a non-string value!") return val.upper() # With py-buzz def buzzy(val: str | int) -> str: return ensure_type(val, str).upper() ``` -------------------------------- ### Executing Logic When No Exception Occurs with do_else Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Demonstrates the use of the `do_else` parameter to specify a callable function that runs only if no exceptions are raised within the `handle_errors` context block. ```python def log_yay(): logger.info("we did it!") with handle_errors("Something went wrong", do_else=log_yay): some_not_dangerous_function() ``` -------------------------------- ### Customize exception details for type mismatches with py-buzz Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Illustrates how to use `ensure_type()` to raise custom exception classes with specific positional and keyword arguments when a value's type does not match the expected type, providing detailed error context. ```python def neopolitan(val: str | int): return ensure_type( val, str, "Received a non-string value!" raise_exc_class=MyProjectError, raise_args=["jawa", "ewok"], raise_kwargs=dict(hutt="pyke"), ) ``` -------------------------------- ### Executing Custom Logic on Exception with do_except Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Shows how to provide a callable function to the `do_except` parameter. This function is executed when an exception is caught and receives a `DoExceptParams` object containing details about the error, useful for logging or custom error processing. ```python def log_error(dep: DoExceptParams): logger.error(dep.final_message) logger.error('\n'.join(dep.trace)) with handle_errors("Something went wrong", do_except=log_error): some_dangerous_function() ``` -------------------------------- ### Specify Custom Exception Type with `raise_exc_class` Source: https://github.com/dusktreader/py-buzz/blob/main/docs/source/features.md Shows how to use the `raise_exc_class` parameter in `require_condition()` to specify a custom exception type that should be raised if the condition fails, instead of the default `Exception`. ```python require_condition( some_condition(), "some_condition failed", raise_exc_class=MyProjectError, ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.