Skip to main content

Rust-inspired Result type for Python with pattern matching and type-safe error handling

Project description

philiprehberger-result

Tests PyPI version License

Rust-inspired Result type for Python with pattern matching and type-safe error handling.

Installation

pip install philiprehberger-result

Usage

Basic Result

from philiprehberger_result import Ok, Err, Result

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

result = divide(10, 2)
print(result.unwrap())  # 5.0

result = divide(10, 0)
print(result.unwrap_or(0.0))  # 0.0

Pattern Matching (Python 3.10+)

match divide(10, 3):
    case Ok(value):
        print(f"Result: {value}")
    case Err(error):
        print(f"Error: {error}")

Chaining

result = (
    Ok(10)
    .map(lambda x: x * 2)
    .flat_map(lambda x: Ok(x + 1) if x < 100 else Err("too large"))
)

Fallback with or_else

result = Err("not found").or_else(lambda e: Ok("default"))
# Ok("default")

Serialization

Ok(42).to_dict()    # {"ok": 42}
Err("x").to_dict()  # {"err": "x"}

Try/Catch Wrapping

from philiprehberger_result import try_catch

result = try_catch(lambda: int("not a number"))
# Err(ValueError("invalid literal..."))

Async Support

from philiprehberger_result import try_catch_async

result = await try_catch_async(fetch_data)

Collecting Results

from philiprehberger_result import all_ok

results = [Ok(1), Ok(2), Ok(3)]
combined = all_ok(results)  # Ok([1, 2, 3])

results = [Ok(1), Err("fail"), Ok(3)]
combined = all_ok(results)  # Err("fail")

API Reference

Function / Class Description
Ok(value) Success variant — wraps a value
Err(error) Error variant — wraps an error
.is_ok() / .is_err() Type check
.unwrap() Get value or raise
.unwrap_or(default) Get value or return default
.unwrap_err() Get error or raise
.map(fn) Transform Ok value
.map_err(fn) Transform Err value
.flat_map(fn) Chain Result-returning functions
.or_else(fn) Fallback on Err, pass-through on Ok
.match(ok=fn, err=fn) Pattern dispatch
.to_dict() Serialize to {"ok": v} or {"err": e}
ok(value) / err(error) Shorthand constructors
try_catch(fn) Wrap callable in Result
try_catch_async(fn) Async version
from_awaitable(aw) Wrap awaitable in Result
all_ok(results) Collect list of Results into Result of list

Development

pip install -e .
python -m pytest tests/ -v

License

MIT

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

philiprehberger_result-0.2.4.tar.gz (5.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

philiprehberger_result-0.2.4-py3-none-any.whl (4.8 kB view details)

Uploaded Python 3

File details

Details for the file philiprehberger_result-0.2.4.tar.gz.

File metadata

  • Download URL: philiprehberger_result-0.2.4.tar.gz
  • Upload date:
  • Size: 5.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for philiprehberger_result-0.2.4.tar.gz
Algorithm Hash digest
SHA256 64fcffc31974fe825bc8a7d2e92e87c61a80330c911d9c2f4ac5713654b14aba
MD5 8f8daa12def4b047402c0467bfa3d976
BLAKE2b-256 938841f8a608cc44d511c29066206db60569998aa1d91b47c0528c41b68e8538

See more details on using hashes here.

File details

Details for the file philiprehberger_result-0.2.4-py3-none-any.whl.

File metadata

File hashes

Hashes for philiprehberger_result-0.2.4-py3-none-any.whl
Algorithm Hash digest
SHA256 b882e994d3482be5625670d6a67c66bd7cea9869d2970525348f5249a2e6501a
MD5 6ab373aa6bcfdbf4e56af2d0c17f988d
BLAKE2b-256 2817439d52803e1200fd07cf32e05153df8f4aad65ecb5bbe443394576bd3609

See more details on using hashes here.

Supported by

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