Skip to main content

rezult

Rust-inspired Result, Option, and panic for Python 3.12 +.

rezult makes failure and absence part of the type signature. Instead of throwing exceptions and hoping every caller remembers to catch them, a function returns Ok(value) or Err(error), and callers handle both cases explicitly with pattern matching or the built-in combinators.

rezult is independent, which means it have no extra dependencies. As a result, it is lightweight and fast.

Why not try - except?

Exceptions are invisible in a function signature. Nothing stops an error from escaping several layers up the stack, and the caller has no way to know which failures are expected without reading the implementation.

def parse_age(text: str) -> int:
    try:
        age = int(text)
    except ValueError as exc:
        raise RuntimeError("invalid age") from exc
    if age < 0:
        raise ValueError("age must be non-negative")
    return age


try:
    age = parse_age("abc")
except RuntimeError as exc:
    print(f"failed: {exc}")

With rezult, the failure is part of the return type and the caller handles it in one place:

from rezult import Err, Ok, resulty


@resulty(ValueError)
def parse_age(text: str) -> int:
    age = int(text)
    if age < 0:
        raise ValueError("age must be non-negative")
    return age


match parse_age("abc"):
    case Ok(age):
        print(f"age = {age}")
    case Err(error):
        print(f"failed: {error}")

The main differences:

try / except rezult
Failure visible in the signature No Yes
Handling failures Optional, easy to forget Explicit match or unwrap
Chaining fallible steps Nested try blocks map, map_err, and_then_res, or_else_res
Distinguishing "no value" from "error" None and exceptions get mixed up Separate Option and Result types
Unrecoverable states raise something a caller may swallow panic prints and exits
Testing Must assert on exceptions Compare values directly

Notice that rezult is designed for providing a pratical way to handle exceptions more tersely, but not taking the place for exceptions such as KeyboardInterrupted which contain a specified sematic meaning. That is also why the capturing helpers only catch Exception: a BaseException such as KeyboardInterrupt, SystemExit, or PanicError always propagates, and panic is there for the states a program cannot continue from.

Installation

# pip
pip install rezult

# uv
uv add rezult

# uv pip
uv pip install rezult

or, from a checkout:

pip install .

Requires Python 3.12 or newer.

Quick start

Result

from rezult import Err, Ok, Result


def divide(a: float, b: float) -> Result[float, str]:
    if b == 0:
        return Err("division by zero")
    return Ok(a / b)


match divide(10, 2):
    case Ok(value):
        print(f"result: {value}")   # result: 5.0
    case Err(error):
        print(f"error: {error}")


match divide(1, 0):
    case Ok(value):
        print(f"result: {value}")
    case Err(error):
        print(f"error: {error}")    # error: division by zero

Results compose without nested try blocks:

def validate(age: int) -> Result[int, str]:
    return Ok(age) if age >= 18 else Err("too young")


result = (
    divide(36, 2)
    .map(int)
    .and_then_res(validate)
)
print(result)  # Ok(18)

print(divide(1, 0).map_err(str).unwrap_or(-1))  # -1

Other useful methods include is_ok(), is_err(), ok(), err(), map_or(), inspect(), unwrap(), expect(), or_res(), and or_else_res().

Option

Option[T] is either Some(value) or Nothing(). Nothing() is a singleton, so it can be checked with is.

from rezult import Nothing, Option, Some


def find_user(user_id: int) -> Option[str]:
    users = {1: "alice", 2: "bob"}
    return Some(users[user_id]) if user_id in users else Nothing()


match find_user(1):
    case Some(name):
        print(f"hello, {name}")     # hello, alice
    case Nothing():
        print("user not found")


print(find_user(3).unwrap_or("anonymous"))  # anonymous

Options chain in the same way:

from functools import partial
from operator import ne

find_user(1).map(str.upper)                 # Some('ALICE')
find_user(1).filter(partial(ne, "alice"))   # Nothing
find_user(3).or_opt(Some("guest"))          # Some('guest')

Other useful methods include is_some(), is_none(), ok_or(), map_or(), map_or_else(), and_then_opt(), or_else_opt(), xor(), zip(), and unwrap().

Decorators

resulty turns raised exceptions into Err values:

from pathlib import Path

from rezult import resulty


@resulty()
def load(path: str) -> str:
    return Path(path).read_text()


@resulty(ValueError, KeyError)
def lookup(data: dict[str, int], key: str) -> int:
    return data[key]


load("missing.txt")          # Err(FileNotFoundError(...))
lookup({"a": 1}, "b")        # Err(KeyError('b'))

optionally turns a None return value into Nothing():

from rezult import optionally


@optionally
def first(items: list[int]) -> int | None:
    return items[0] if items else None


first([1, 2])  # Some(1)
first([])      # Nothing

Both decorators preserve the wrapped function's metadata. Decorating an async function is a usage error: they panic with a TypeError instead of silently returning an un-awaited coroutine.

resulty and result_eval capture Exception subclasses only, so KeyboardInterrupt, SystemExit, and PanicError pass straight through.

Evaluating expressions

If you already have a callable, use result_eval or option_eval:

from rezult import option_eval, result_eval

result_eval(lambda: 1 / 0)      # Err(ZeroDivisionError('division by zero'))
result_eval(int, "42")          # Ok(42)
option_eval(lambda: None)       # Nothing
option_eval(lambda: "value")    # Some('value')

Panic

Result and Option are for failures a caller can recover from. panic is the deliberate abort for the rest: it prints a traceback to stderr and exits the interpreter with a non-zero status (-1 by default), so no handler up the stack can turn a broken invariant into an ordinary return value.

from rezult import panic


def ratio(a: float, b: float) -> float:
    if b == 0:
        panic("ratio() called with a zero denominator")
    return a / b

Running that with a zero denominator prints the caller's stack, formatted by traceback, and nothing after the panic call runs:

Traceback (most recent call last):
  File "app.py", line 12, in <module>
    ratio(1, 0)
  File "app.py", line 8, in ratio
    panic("ratio() called with a zero denominator")
rezult.panic.PanicError: ratio() called with a zero denominator

Only the caller's frames are reported; panic never shows up in its own traceback. The status is truncated by the OS, so POSIX shells report the default -1 as 255; rely on the exact value only when you set code yourself.

The reported error defaults to PanicError. Note that it is printed rather than raised: a try / except PanicError never sees it, the process simply stops. Pass exception to swap in your own error type and code to change the exit status:

from rezult import panic


class ConfigError(Exception):
    pass


panic("missing DATABASE_URL", exception=ConfigError, code=78)
# ConfigError: missing DATABASE_URL   (exit status 78)

An exception instance can also be used as the message, and is reported unchanged:

panic(ValueError("bad config"))
# ValueError: bad config

PanicError derives from BaseException rather than Exception, which is why except Exception, resulty, and result_eval all let a panic through instead of wrapping it in Err:

@resulty()
def load(path: str) -> str:
    if not path:
        panic("empty path")
    return Path(path).read_text()


load("")   # prints the panic and exits; it never returns Err(...)

panic is annotated as returning Never, so type checkers know that the code after it is unreachable:

def unwrap_value(option: Option[int]) -> int:
    match option:
        case Some(value):
            return value
        case Nothing():
            panic("unwrap_value() called on Nothing()")

API at a glance

Export Description
Ok(value) Successful Result variant
Err(error) Failed Result variant
Some(value) Non-empty Option variant
Nothing() Empty Option variant (singleton)
Result Base class and combinators for fallible values
Option Base class and combinators for optional values
UnwrapError Raised by unwrap, expect, unwrap_err, and expect_err
resulty(...) Decorator: exceptions become Err
optionally Decorator: None becomes Nothing()
result_eval(expr, *args, **kwargs) Evaluate a callable, capturing exceptions as Err
option_eval(expr, *args, **kwargs) Evaluate a callable, converting None to Nothing()
panic(msg, *, exception=None, code=-1) Print a traceback ending in the error, then exit with code
PanicError Default error reported by panic; a BaseException, not an Exception

Both types support structural pattern matching, equality by variant and contained value, and hashing.

Contributing

We allow all kinds of contributions, except for fully AI generated code and contributions that only contain a little human thinking.

License

MIT

Metadata

Release files for rezult 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for rezult 0.4.0
File Size Uploaded Provenance Actions
rezult-0.4.0.tar.gz 13.0 kB Without provenance Details for rezult-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for rezult 0.4.0
File Interpreter ABI Platform Actions
rezult-0.4.0-py3-none-any.whl Python 3 none any Details for rezult-0.4.0-py3-none-any.whl

Total release size: 27.9 kB

Release files / rezult-0.4.0.tar.gz

Download URL rezult-0.4.0.tar.gz
Size 13.0 kB
Tags Source
SHA-256 checksum
How to use checksums
967ffa2be4034ecf721092766f6cb79e6102369af682ed160ee4af1cc363094a
BLAKE2b-256 checksum
How to use checksums
081f4e01ec90333e2d9ca5b3aeccdd29f5dd37aadb9ae86573cce02057bc296d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / rezult-0.4.0-py3-none-any.whl

Download URL rezult-0.4.0-py3-none-any.whl
Size 14.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fe97a440fe5e583e96e19f2cf19ac1fd745c5aaa0fcf794146042c06e2e68bae
BLAKE2b-256 checksum
How to use checksums
6b1aa49b97ba2d244e5e526edccb3158980df16c095f76b8da9a05734b8b888a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for rezult 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page