Rust's Result and Option in python
Project description
Resulting
Bring the rust Result and Option type into python.
pip install resulting
Result
from resulting import Result, Ok, Err
def get_user_id() -> Result[int, str]:
return Ok(123)
match get_user():
case Ok(user_id):
print(f"User ID: {user_id}")
case Err(msg):
print(f"Failed to get user: {msg}")
Tracebacks
When unwrapping a Result or Option, a traceback will be inserted up to the place the `Err`` was created
This allows you to have the powerful debugging of Exceptions with guarentees of results
# example.py
from resulting import Err
def create_err() -> Err[str]:
return Err("Throw Me!")
res = create_err()
res.unwrap()
Traceback (most recent call last):
File "/example.py", line 7, in <module>
res.unwrap()
File "/example.py", line 6, in <module>
res = create_err()
File "/example.py", line 4, in create_err
return Err("Throw Me!")
RuntimeError: Unwrapped Err(Throw Me!)
Option
from resulting import Option, Some, none
def get_user_id() -> Option[int]:
return Some(123)
match get_user():
case Some(user_id):
print(f"User ID: {user_id}")
case none():
print(f"User does not exist")
Catch Errors
You can use the safe
decorator to catch exceptions
from resulting import safe
@catch()
def get_user() -> str:
raise KeyError("User Not Found")
res: Result[str, Exception] = get_user()
or catch specific exceptions using catch
from resulting import catch
@catch([KeyError, LookupError])
def get_user() -> str:
raise KeyError("User Not Found")
res: Result[str, KeyError|LookupError] = get_user()
Optional
from resulting import optional
@optional
def get_user() -> str|None:
return "1"
res: Option[str] = get_user()
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
resulting-1.1.1.tar.gz
(6.0 kB
view hashes)
Built Distribution
Close
Hashes for resulting-1.1.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | cb296838f0edbd265c8739ad9e902228ed37b9988d8f448782a62f2c52ebd469 |
|
MD5 | 8fac05bd48138cab7e22b586d339b7b5 |
|
BLAKE2b-256 | c384ee0b9ce806528473ba9efa99c294e2a20193f314952f0cd1fbd5bbf2fd07 |