Rust-like Result Type for Python

0.17.0 · abandoned · verified Sat Apr 11

The `result` library provides a Rust-inspired `Result` type for Python 3, enabling explicit error handling without relying solely on exceptions. It introduces `Ok` and `Err` classes to encapsulate success and failure values, respectively, and is fully type-annotated. The current version is 0.17.0, but the library is explicitly marked as 'NOT MAINTAINED' by its authors.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a function that returns a `Result` type, indicating either a successful operation with `Ok(value)` or a failure with `Err(error)`. It shows how to safely unwrap the result using `isinstance` checks or the provided `is_ok`/`is_err` type guards. For Python 3.10 and newer, structural pattern matching (`match` statement) offers a more elegant way to handle `Result` types.

from result import Ok, Err, Result, is_ok

def divide(a: int, b: int) -> Result[float, str]:
    if b == 0:
        return Err("Cannot divide by zero")
    return Ok(a / b)

# Example usage with isinstance
div_result = divide(10, 2)
if isinstance(div_result, Ok):
    print(f"Division successful: {div_result.ok_value}")
else:
    print(f"Division failed: {div_result.err_value}")

div_result_fail = divide(10, 0)
if is_ok(div_result_fail):
    print(f"Division successful: {div_result_fail.ok_value}")
else:
    print(f"Division failed: {div_result_fail.err_value}")

# Example usage with pattern matching (Python 3.10+)
# This is commented out to ensure compatibility with Python < 3.10 for execution, 
# but is a recommended pattern for newer Python versions.
# def process_division(a: int, b: int):
#     match divide(a, b):
#         case Ok(value):
#             print(f"{a} / {b} == {value}")
#         case Err(error_message):
#             print(f"Error: {error_message}")
# process_division(10, 5)
# process_division(10, 0)

view raw JSON →