Agnostic-language library to use Result and Option from Rust
Project description
Accord
Accord brings the robust error handling and optional value patterns from Rust's Result and Option types to Python. This library provides a type-safe way to handle operations that can fail or may not have a value, leading to more predictable and maintainable code.
We intend not to use any kind of non-std library on Accord, so we do not need any extra dependency as a drawback for using it.
Why "Accord"?
The tale I weave for you now is about a puppet that travels the world.
The puppet's goal is to observe how humans live their lives.
This puppet continues its journey still, carrying its large suitcase with it...
Features
Result<T, E>: Represents either a success (Ok(T)) or a failure (Err(E)).Option<T>: Represents an optional value, being eitherSome(T)orNone.- Ergonomic API: Methods like
map,and_then,or_else,unwrap,expectprovide powerful ways to work with these types. - Type Safety: Leverages Python's type hinting for compile-time checks.
- Sealed Types:
ResultandOptionare sealed, preventing arbitrary subclassing and enforcing usage of provided variants (Ok/Err,Some/None).
Installation
[TBD]
Usage
Result
from accord.result import Result, Ok, Err
def divide(a: int, b: int) -> Result[int, str]:
if b == 0:
return Err("Division by zero is not allowed.")
return Ok(a // b)
# Successful operation
result1 = divide(10, 2)
if result1.is_ok():
print(f"Success: {result1.unwrap()}") # Output: Success: 5
else:
print(f"Error: {result1.unwrap_err()}")
# Failed operation
result2 = divide(10, 0)
if result2.is_ok():
print(f"Success: {result2.unwrap()}")
else:
print(f"Error: {result2.unwrap_err()}") # Output: Error: Division by zero is not allowed.
# Using expect for cleaner unwrap with panic message
try:
value = divide(10, 0).expect("Failed to divide numbers.")
except RuntimeError as e:
print(e) # Output: Failed to divide numbers.: 'Division by zero is not allowed.'
# Chaining operations with and_then
def add_one_if_even(n: int) -> Result[int, str]:
if n % 2 == 0:
return Ok(n + 1)
else:
return Err("Number is odd")
divide(10, 2).and_then(add_one_if_even) # Ok(5) -> add_one_if_even(5) -> Err("Number is odd")
# Returns: Err('Number is odd')
divide(8, 2).and_then(add_one_if_even) # Ok(4) -> add_one_if_even(4) -> Ok(5)
# Returns: Ok(5)
Option
from accord.option import Option, Some, None
def find_user(user_id: int) -> Option[str]:
if user_id == 1:
return Some("Alice")
return None
user1 = find_user(1)
if user1.is_some():
print(f"User found: {user1.unwrap()}") # Output: User found: Alice
else:
print("User not found.")
user2 = find_user(2)
print(f"User: {user2.unwrap_or('Guest')}") # Output: User: Guest
# Using expect
try:
user_name = find_user(2).expect("User with ID 2 not found.")
except RuntimeError as e:
print(e) # Output: User with ID 2 not found.
# Mapping over an Option
user_id_option: Option[int] = Some(123)
mapped_option = user_id_option.map(lambda x: f"User ID: {x}") # Some("User ID: 123")
None.map(lambda x: f"User ID: {x}") # None
# Chaining operations with and_then
def get_user_id_as_str(user_id: int) -> Option[str]:
return Some(str(user_id))
Some(456).and_then(get_user_id_as_str) # Some(456) -> get_user_id_as_str(456) -> Some("456")
# Returns: Some("456")
None.and_then(get_user_id_as_str) # None -> Returns None
# Returns: None
FAQ
Is this README generated by AI?
Yes.
I was feeling lazy. I'll make it myself in the future.
What is Result and Option?
-
Result<T, E>: This type represents the outcome of an operation that might succeed or fail.Ok(T): Indicates success and holds a value of typeT.Err(E): Indicates failure and holds an error value of typeE.- It's Rust's primary way of handling recoverable errors without exceptions.
-
Option<T>: This type represents a value that might be present or absent.Some(T): Indicates that a value of typeTis present.None: Indicates the absence of a value.- It's used for values that are optional, like the result of a search that might not find anything.
Why use Result and Option in Python?
Python traditionally uses exceptions for errors and None for optional values. However, Result and Option offer several benefits:
- Explicit Error Handling:
Resultforces you to consider the error case at compile time (with type checkers) or runtime, making error handling more deliberate than relying on buried exceptions. - Clearer Intent:
Optionmakes it explicit when a value might be missing, distinguishing it from other forms of "empty" or "null" that might arise from different contexts. - Functional Programming Patterns: These types are monadic, enabling elegant chaining of operations using methods like
mapandand_then, leading to more expressive and composable code. - Avoids
NoneAmbiguity: In Python,Nonecan sometimes be ambiguous.Optionclearly separates the absence of a value from other potential "falsy" values.
How do Ok/Err and Some/None relate to Result/Option?
Result and Option are abstract base classes (or type aliases) that define the common interface. Ok and Err are concrete implementations of Result, and Some is a concrete implementation of Option (with None being a singleton for the absence of a value). You will always create an instance of Ok, Err, or Some (or use the None singleton), not directly of Result or Option themselves.
What does "Sealed" mean?
When Result (and Option) are "sealed," it means that only the predefined variants (Ok, Err for Result; Some, None for Option) are allowed to inherit from them. This prevents users of the library from creating their own custom Result or Option types, ensuring that all Result or Option values are one of the intended, known types.
What is the difference between unwrap() and expect()?
unwrap(): Attempts to get the contained value. If the operation fails (ErrorNone), it raises a genericRuntimeError(or the original error forResult.unwrap()).expect(message): Attempts to get the contained value. If the operation fails (ErrorNone), it raises aRuntimeErrorthat includes your custommessagealong with the original error, providing more context about why the operation was expected to succeed.
Contributing
Contributions will be welcomed once we reach the release. Please feel free to open issues or submit pull requests freely then.
License
[TBD]
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file accord_types-0.1.0b2.tar.gz.
File metadata
- Download URL: accord_types-0.1.0b2.tar.gz
- Upload date:
- Size: 21.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c3481dba68bc1a31359c4345a2ddf6adb226fcd208a0e09df7ccb5493ee3aea7
|
|
| MD5 |
daefef169e37a96529cd45691158d2aa
|
|
| BLAKE2b-256 |
a9581cc59e7f5f50527b9c232cdf3b1d4aa884f1c4a647a5c8186deffdab2251
|
File details
Details for the file accord_types-0.1.0b2-py3-none-any.whl.
File metadata
- Download URL: accord_types-0.1.0b2-py3-none-any.whl
- Upload date:
- Size: 17.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6df0679e1a42dccdea6997b947062c461e571b720e1426c24b794cad5dda9dc6
|
|
| MD5 |
80099b0ca1fd2f2ba8eece5e5f460b10
|
|
| BLAKE2b-256 |
f356a2c910ddf4ec3d66349877dc229ad739e67fea2b0be405f44c0845b1366a
|