Skip to main content

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


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)

Uploaded Source

Built Distribution

resulting-1.1.1-py3-none-any.whl (5.9 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page