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 catch
decorator to catch exceptions
from resulting import catch
@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
You can use the optional wrapper to wrap existing functions in an Option
from resulting import optional
@optional
def get_user() -> str|None:
return "1"
res: Option[str] = get_user()
Project details
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.3.0.tar.gz
(6.4 kB
view details)
Built Distribution
File details
Details for the file resulting-1.3.0.tar.gz
.
File metadata
- Download URL: resulting-1.3.0.tar.gz
- Upload date:
- Size: 6.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: python-requests/2.31.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | d19bd13234405316d410e1315e520df88f7469aa6dac784cab56718cf07037fa |
|
MD5 | bfa9f0cf4a23c3f4cd2c39fbd49adc98 |
|
BLAKE2b-256 | 0893137db14b89fc4fae506276c313a1b2e45ce0509ee0b28e88fc9e4f764869 |
File details
Details for the file resulting-1.3.0-py3-none-any.whl
.
File metadata
- Download URL: resulting-1.3.0-py3-none-any.whl
- Upload date:
- Size: 6.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: python-requests/2.31.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2cd67ab69b6cc5bdd3dc49e7a407928b74c197d0ebd09330cf1c5e68ccac81a9 |
|
MD5 | 6331cf591bcaafd93a997603fe116e63 |
|
BLAKE2b-256 | 937e597697bc53c93c097dbe3249399f8e73c1ccc84c2a380a22f92f2b346e08 |