A very simple, fully typed Rust-like Result type for Python 3.
If you need a Result type only for checking if an operation succeeded or failed, and don't need to perform special actions like chaining operations, mapping, etc., then this library is for you.
If you are looking for a more feature-rich Result type, check out rustedpy/result.
# Using pip
pip install simple-result
# Using Poetry
poetry add simple-result
# Using uv
uv add simple-resultimport random
from simple_result import Err, Ok, Result
def fetch_data() -> Result[str, ConnectionError]:
fetched = random.choice([True, False])
if fetched:
return Ok('Data fetched!')
return Err(ConnectionError('Error fetching data!'))Check if the result is Ok or Err using type narrowing:
if res := fetch_data():
print(res.value) # "Data fetched!"
print(res.error) # None
else:
print(res.error) # "Error fetching data!"
print(res.value) # NoneOr using match:
match fetch_data():
case Ok(data):
print(data) # "Data fetched!"
case Err(error):
print(error) # "Error fetching data!"Call .unwrap_value() to get the value or raise an UnwrapError if the result
is Err:
from simple_result import UnwrapError
try:
res = Err(ConnectionError('Error fetching data!'))
print(res.unwrap_value())
except UnwrapError as exc:
print(str(exc)) # called `Result.unwrap_value()` on an `Err` value
print(exc.result.error) # "Error fetching data!"Call .unwrap_error() to get the error or raise an UnwrapError if the result
is Ok:
try:
res = Ok('Data fetched!')
print(res.unwrap_error())
except UnwrapError as exc:
print(str(exc)) # called `Result.unwrap_error()` on an `Ok` value
print(exc.result.value) # "Data fetched!"Compare results:
assert Ok(1) == Ok(1)
assert Ok(1) != Ok(2)
exc = ValueError('error')
assert Err(exc) == Err(exc)
other_exc = ValueError('other error')
assert Err(exc) != Err(other_exc)Check if the result is Ok or Err using isinstance:
from simple_result import ResultOption
res = fetch_data()
assert isinstance(res, ResultOption)
assert isinstance(res, (Ok, Err))See the contribution guidelines.
This project is licensed under the MIT License. See the LICENSE file for details.
If you find this project useful, give it a ⭐ on GitHub!