module rustico
Global Variables
- OkErr
function as_result
Decorator that converts a function to return Result, catching specified exceptions as Err.
Use when you want to convert exception-based APIs to Result-based APIs. Essential for integrating with existing codebases. Avoid when functions already return Results.
@as_result(ValueError)
def parse_int(x: str) -> int:
return int(x)
parse_int("42") # Ok(42)
parse_int("fail") # Err(ValueError(...))
function as_async_result
as_async_result(
*exceptions: 'type[BE]'
) → Callable[[Callable[, Awaitable[T]]], Callable[, Awaitable[Result[T, BE]]]]
Decorator that converts an async function to return Result, catching specified exceptions as Err.
Use when you want to convert async exception-based APIs to Result-based APIs. Essential for integrating async codebases. Avoid when async functions already return Results.
function is_ok
Type guard that returns True if the result is Ok, providing type narrowing.
Use for type-safe conditional logic and when you need type narrowing. Essential for type checkers. Prefer result.is_ok() for simple boolean checks.
function is_err
Type guard that returns True if the result is Err, providing type narrowing.
Use for type-safe conditional logic and when you need type narrowing. Essential for type checkers. Prefer result.is_err() for simple boolean checks.
function match
match(
result: 'Result[T, E]',
ok_handler: 'Callable[[T], T]',
err_handler: 'Callable[[E], T] | None' = None
) → T | None
Pattern match on a Result and apply the appropriate handler function.
This function provides a functional, explicit alternative to Python's pattern matching syntax, allowing you to handle both success (Ok
) and error (Err
) cases with dedicated handler functions. It's especially useful when you want to transform or branch on the contents of a Result without unwrapping it or writing conditional logic.
When to use:
- When you want to handle both success and error cases in a single, readable expression.
- When you want to transform a Result into another value or type, e.g., for logging, formatting, or fallback logic.
- When you want to avoid try/except
and keep error handling explicit and composable.
When not to use:
- When you only care about the success value and want to fail fast (use unwrap
or unwrap_or
).
- When you only want to transform the success or error value (use map
or map_err
).
- When you need to propagate the Result further without handling it yet.
result = get_user_age() # Returns Result[int, str]
formatted = match(
result,
ok_handler=lambda age: f"User is {age} years old",
err_handler=lambda err: f"Error getting age: {err}"
)
# Ok case: "User is 25 years old"
# Err case: "Error getting age: Invalid user data"
function do
do(
fn_or_gen: 'Callable[, Generator[Result[T, E], T | None, T]] | Generator[Result[T, E], T | None, T]'
) → Callable[[], Result[T, E]] | Result[T, E]
Dual-purpose function for emulating do-notation with Result types.
Use as a decorator for functions that yield Results, or as a helper for generators. Essential for imperative-style Result handling. Avoid when simple chaining suffices. Can be used as a decorator or called directly with a generator instance.
function do_async
do_async(
fn_or_gen: 'Callable[, AsyncGenerator[Result[T, E], None]] | AsyncGenerator[Result[T, E], None]'
) → Callable[, Awaitable[Result[T, E]]] | Awaitable[Result[T, E]]
Dual-purpose function for emulating async do-notation with Result types.
Use as a decorator for async functions that yield Results, or as a helper for async generators. Essential for imperative-style async Result handling. Avoid when simple async chaining suffices. Can be used as a decorator or called directly with an async generator instance.
function catch
Decorator that catches specified exceptions and returns them as Err Results.
Use when you want to convert specific exceptions to Results without catching all exceptions. More precise than as_result for targeted exception handling. Avoid when you need to catch all exceptions.
function catch_async
catch_async(
*exceptions: 'type[BE]'
) → Callable[[Callable[, Awaitable[T]]], Callable[, Awaitable[Result[T, BE]]]]
Decorator that catches specified exceptions in async functions and returns them as Err Results.
Use when you want to convert specific async exceptions to Results without catching all exceptions. More precise than as_async_result for targeted exception handling. Avoid when you need to catch all exceptions.
class UnwrapError
Exception raised when an unwrap or expect operation fails on a Result.
try:
Err("fail").unwrap()
except UnwrapError as e:
print(e)
# Called `Result.unwrap()` on an `Err` value: 'fail'
method __init__
property result
Returns the original result that caused the unwrap failure.
Useful for debugging and error recovery scenarios where you need to inspect the original Result that failed to unwrap. Common in error handling pipelines where you want to log the original error context.
class Ok
Represents a successful result containing a value.
Use when operations succeed and you want to chain further operations. Avoid when you need to represent failure states - use Err instead.
method __init__
property ok_value
Returns the inner value for pattern matching and direct access.
Use with match statements and when you need direct property access. Prefer unwrap() for general value extraction. Avoid when error handling is needed.
method alt
No-op for Ok instances - error transformation doesn't apply to successful results.
Use in generic code that handles both Ok and Err. The operation is ignored for Ok instances, maintaining the original value. Avoid when you know the Result is Ok.
method and_then
Chains another Result-returning operation on the contained value (monadic bind).
Use for chaining operations that can fail, creating pipelines of fallible computations. Essential for functional error handling. Avoid when the operation cannot fail.
method and_then_async
Asynchronously chains another Result-returning operation on the contained value.
Use for chaining async operations that can fail. Essential for async functional error handling patterns. Avoid when the async operation cannot fail.
method err
Always returns None for Ok instances since there's no error.
Use for symmetry with Err.err() in generic code. Avoid when you know the Result is Ok - the return will always be None.
method expect
Returns the contained value, ignoring the message since Ok cannot fail.
Use when you want consistent API with Err.expect() in generic code. Prefer unwrap() when you know the Result is Ok. Avoid when error context isn't needed.
method expect_err
Always raises UnwrapError since Ok instances don't contain errors.
Use when you expect an error but got success - indicates a logic error. Common in testing scenarios. Avoid in normal business logic.
method inspect
Calls the provided function with the contained value for side effects, returns self.
Use for debugging, logging, or other side effects without changing the Result. Common for tracing successful values in pipelines. Avoid when side effects are expensive.
method inspect_err
No-op for Ok instances - error inspection doesn't apply to successful results.
Use in generic code that handles both Ok and Err. The operation is ignored for Ok instances. Avoid when you know the Result is Ok.
method is_err
Always returns False for Ok instances.
Use for type narrowing and conditional logic. Prefer this over isinstance checks for better type inference. Avoid when you already know the Result type.
method is_ok
Always returns True for Ok instances.
Use for type narrowing and conditional logic. Prefer this over isinstance checks for better type inference. Avoid when you already know the Result type.
method map
Transforms the contained value using the provided function, wrapping result in Ok.
Use for transforming successful values while preserving the Ok context. Essential for functional programming patterns. Avoid when transformation can fail without proper error handling.
method map_async
Asynchronously transforms the contained value, wrapping result in Ok.
Use for async transformations of successful values. Essential for async functional programming patterns. Avoid when the async operation can fail without proper error handling.
method map_err
No-op for Ok instances - error transformation doesn't apply to successful results.
Use in generic code that handles both Ok and Err. The operation is ignored for Ok instances, maintaining the original value. Avoid when you know the Result is Ok.
method map_or
Transforms the contained value using the operation, ignoring the default.
Use when you want consistent API with Err.map_or() in generic code. The default is never used for Ok instances. Prefer map() when you know the Result is Ok.
method map_or_else
Transforms the contained value using the operation, ignoring the default operation.
Use when you want consistent API with Err.map_or_else() in generic code. The default operation is never called for Ok instances. Prefer map() when you know the Result is Ok.
method match
Pattern matches on Ok, requiring an 'ok' handler and ignoring 'err' handler.
Use for exhaustive pattern matching with clear intent. Provides type safety and forces explicit handling. Avoid when simple unwrap() or map() suffices.
method ok
Returns the contained value for Ok instances.
Use when you want to extract the value without unwrapping. Prefer unwrap() when you're certain the Result is Ok. Avoid when you need error handling.
method or_else
No-op for Ok instances - error recovery doesn't apply to successful results.
Use in generic code that handles both Ok and Err. The operation is ignored for Ok instances, maintaining the original value. Avoid when you know the Result is Ok.
method unwrap
Returns the contained value safely since Ok instances always contain values.
Use when you're certain the Result is Ok or when you want to fail fast on errors. Prefer this over ok() for value extraction. Avoid when error handling is required.
method unwrap_err
Always raises UnwrapError since Ok instances don't contain errors.
Use when you expect an error but got success - indicates a logic error. Common in testing scenarios. Avoid in normal business logic.
method unwrap_or
Returns the contained value, ignoring the default since Ok always has a value.
Use when you want consistent API with Err.unwrap_or() in generic code. Prefer unwrap() when you know the Result is Ok. Avoid when the default is expensive.
method unwrap_or_else
Returns the contained value, ignoring the operation since Ok always has a value.
Use when you want consistent API with Err.unwrap_or_else() in generic code. The operation is never called for Ok instances. Avoid when you know the Result is Ok.
method unwrap_or_raise
Returns the contained value, ignoring the exception since Ok cannot fail.
Use when you want consistent API with Err.unwrap_or_raise() in generic code. The exception is never raised for Ok instances. Avoid when you know the Result is Ok.
method value_or
Returns the contained value, ignoring the default (alias for unwrap_or).
Use when you want consistent API with Err.value_or(). Prefer unwrap() when you know the Result is Ok. Avoid when the default value is expensive to compute.
class Err
Represents a failed result containing an error value.
Use when operations fail and you want to propagate error information. Avoid when success is the only meaningful outcome.
method __init__
property err_value
Returns the inner error value for pattern matching and direct access.
Use with match statements and when you need direct property access. Prefer unwrap_err() for general error extraction. Avoid when success handling is needed.
property trace
Returns the captured stack trace as a list of formatted strings for BaseException errors.
Use for debugging and error reporting when the error value is an exception. Computed lazily to avoid performance overhead. Returns None for non-exception errors. Avoid when error value is not an exception.
try: raise ValueError("fail") except ValueError as e: err = Err(e) print(err.trace)
method alt
Transforms the contained error value using the provided function, wrapping result in Err.
Use for transforming error values while preserving the Err context. Common for error normalization and enrichment. Avoid when error transformation can fail without proper handling.
method and_then
No-op for Err instances - chaining operations doesn't apply to failed results.
Use in generic code that handles both Ok and Err. The operation is ignored for Err instances, maintaining the original error. Avoid when you know the Result is Err.
method and_then_async
No-op for Err instances - async chaining operations doesn't apply to failed results.
Use in generic code that handles both Ok and Err. The operation is ignored for Err instances, maintaining the original error. Avoid when you know the Result is Err.
method err
Returns the contained error value for Err instances.
Use when you want to extract the error without unwrapping. Prefer unwrap_err() when you're certain the Result is Err. Avoid when you need success handling.
method expect
Always raises UnwrapError with the provided message since Err instances represent failure.
Use when you expect success but got failure - provides clear error context. Common for assertions and fail-fast scenarios. Avoid in normal error handling.
method expect_err
Returns the contained error value, ignoring the message since Err always contains errors.
Use when you want consistent API with Ok.expect_err() in generic code. Prefer unwrap_err() when you know the Result is Err. Avoid when success context isn't needed.
method inspect
No-op for Err instances - value inspection doesn't apply to failed results.
Use in generic code that handles both Ok and Err. The operation is ignored for Err instances. Avoid when you know the Result is Err.
method inspect_err
Calls the provided function with the contained error value for side effects, returns self.
Use for debugging, logging, or other side effects without changing the Result. Common for tracing error values in pipelines. Avoid when side effects are expensive.
method is_err
Always returns True for Err instances.
Use for type narrowing and conditional logic. Prefer this over isinstance checks for better type inference. Avoid when you already know the Result type.
method is_ok
Always returns False for Err instances.
Use for type narrowing and conditional logic. Prefer this over isinstance checks for better type inference. Avoid when you already know the Result type.
method map
No-op for Err instances - value transformation doesn't apply to failed results.
Use in generic code that handles both Ok and Err. The operation is ignored for Err instances, maintaining the original error. Avoid when you know the Result is Err.
method map_async
No-op for Err instances - async value transformation doesn't apply to failed results.
Use in generic code that handles both Ok and Err. The operation is ignored for Err instances, maintaining the original error. Avoid when you know the Result is Err.
method map_err
Transforms the contained error value using the provided function, wrapping result in Err.
Use for transforming error values while preserving the Err context. Common for error normalization and enrichment. Avoid when error transformation can fail.
method map_or
Returns the default value since Err instances don't contain success values to transform.
Use when you want to provide a fallback value instead of transforming. The operation is ignored for Err instances. Avoid when the default is expensive.
method map_or_else
Calls the default operation since Err instances don't contain success values to transform.
Use when you want to compute a fallback value for failed results. The main operation is ignored for Err instances. Avoid when the default operation is expensive.
method match
Pattern matches on Err, requiring an 'err' handler and ignoring 'ok' handler.
Use for exhaustive pattern matching with clear intent. Provides type safety and forces explicit handling. Avoid when simple unwrap_err() or map_err() suffices.
method ok
Always returns None for Err instances since there's no success value.
Use for symmetry with Ok.ok() in generic code. Avoid when you know the Result is Err - the return will always be None.
method or_else
Applies error recovery operation to the contained error value (monadic bind for errors).
Use for chaining error recovery operations, creating pipelines of error handling. Essential for functional error recovery patterns. Avoid when the operation cannot fail.
method unwrap
Always raises UnwrapError since Err instances don't contain success values.
Use when you expect success but got failure - indicates a logic error. Common for fail-fast scenarios and debugging. Avoid in normal error handling.
The unwrap()
method is powerful but should be used with caution. It's designed for situations where you are certain the Result
holds a successful value (Ok
).
- If you call
result.unwrap()
on anOk
instance, it safely returns the contained value. * However, if you callresult.unwrap()
on anErr
instance, it will raise anUnwrapError
exception. This is a "fail-fast" mechanism, indicating an unexpected error or a logical flaw in your code.
For robust error handling where you expect and want to gracefully manage potential errors, prefer using methods like is_ok()
, is_err()
, unwrap_or()
, unwrap_or_else()
, and_then()
, or Python's match
statement to process the Result
without risking an exception.
method unwrap_err
Returns the contained error value safely since Err instances always contain errors.
Use when you're certain the Result is Err or when you want to fail fast on success. Prefer this over err() for error extraction. Avoid when success handling is required.
method unwrap_or
Returns the default value since Err instances don't contain success values.
Use when you want to provide a fallback value for failed operations. Essential for graceful degradation patterns. Avoid when the default is expensive to compute.
method unwrap_or_else
Applies the operation to the error value and returns the result.
Use when you want to compute a fallback value based on the error. Essential for error recovery patterns. Avoid when the operation is expensive or can fail.
method unwrap_or_raise
Raises the provided exception type with the error value as the message.
Use when you want to convert Result errors to traditional exceptions. Common at API boundaries. Avoid when you want to maintain Result-based error handling.
method value_or
Returns the default value since Err instances don't contain success values.
Use when you want to provide a fallback value for failed operations. Essential for graceful degradation patterns. Avoid when the default is expensive to compute.
This file was automatically generated via lazydocs.