Rust-like Result Type for Python
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
- breaking The `rustedpy/result` library is explicitly marked as 'NOT MAINTAINED' on its GitHub repository. This means there will be no further development, bug fixes, or security updates. Projects relying on this library may face compatibility issues with newer Python versions or unaddressed vulnerabilities.
- gotcha Attempting to access `.ok_value` on an `Err` instance or `.err_value` on an `Ok` instance will result in an `AttributeError`. The `Ok` and `Err` classes are slotted (`__slots__`), preventing arbitrary attribute assignment and making instances immutable.
- gotcha MyPy may sometimes struggle with type inference for `Result` types in certain scenarios, leading to 'Cannot infer type argument' errors.
Install
-
pip install result
Imports
- Ok
from result import Ok
- Err
from result import Err
- Result
from result import Result
- is_ok
from result import is_ok
- is_err
from result import is_err
Quickstart
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)