py-better-result
A small Python port of the Rust retry-result crate, with an immutable
Result[T, E] implementation shaped after Rust's std::result::Result.
from better_result import Err, Ok, RetryPolicy, retry
attempts = 0
def request() -> Ok[str] | Err[str]:
global attempts
attempts += 1
return Err("temporary") if attempts < 2 else Ok("done")
result = retry(request, RetryPolicy.fixed(2, 0))
assert result == Ok("done")
Result
Ok(value) and Err(error) are immutable result variants. The supported
operations follow Rust's Result API:
- inspection:
is_ok,is_err,is_ok_and,is_err_and,ok,err - mapping:
map,map_or,map_or_else,map_err - composition:
and_,and_then,or_,or_else - observation:
inspect,inspect_err - extraction:
unwrap,expect,unwrap_err,expect_err,unwrap_or,unwrap_or_else,unwrap_or_default
Python uses and_ and or_ because and and or are reserved keywords.
Callback exceptions are not silently converted to Err values.
Capture exceptions
Python functions often signal expected failures by raising exceptions. Use
capture at that boundary to turn a one-shot operation into a Result:
from better_result import capture
result = capture(lambda: int("not-a-number"), catch=str)
assert result.err() == "invalid literal for int() with base 10: 'not-a-number'"
Without catch, the original Exception is stored in Err. The mapper is
where the exception should be translated into the domain error type for the
current layer. Mapper failures are not captured. capture_async provides the
same behavior for async operations and also accepts an async mapper. Pass
exceptions=(TimeoutError, OSError) to capture only selected failures. Only
Exception is captured, so asyncio.CancelledError and other BaseException
values propagate normally.
Capture is deliberately an explicit boundary rather than behavior baked into
Result.map or retry: callback and programmer errors should not silently
become domain failures.
Retry
Retry operates on Result-returning operations. Wrap exception-based
operations with capture when they need retrying:
from better_result import RetryPolicy, try_result
result = try_result(
read_config,
RetryPolicy.immediate(2),
catch=str,
)
try_result and try_async combine capture and retry for ordinary
exception-based functions. Pass exceptions=(TimeoutError, OSError) to
capture only expected failures; uncaught programmer errors still propagate.
The is_ok and is_err helpers are type guards, so type checkers narrow a
Result[T, E] to Ok[T] or Err[E] inside each branch.
Expected failures should be returned as Err after crossing the boundary.
from better_result import Err, Ok, RetryPolicy, retry
policy = RetryPolicy.exponential(3, 0.01, 2)
attempts = 0
def operation() -> Ok[str] | Err[str]:
global attempts
attempts += 1
return Err("temporary") if attempts < 3 else Ok("response")
result = retry(operation, policy)
assert result == Ok("response")
Available schedules are FixedBackoff, LinearBackoff,
ExponentialBackoff, and Jittered. Custom schedules implement
decide(RetryContext) -> RetryDecision; custom predicates implement
should_retry(RetryContext) -> bool.
Retry delays are finite, non-negative floating-point seconds, representing
Rust's Duration. Invalid exponential multipliers and jitter factors raise
InvalidBackoffMultiplier and InvalidJitterFactor, respectively.
retry_async provides the same behavior for awaitable operations. Normal
asyncio task cancellation cancels an in-flight operation or retry delay.
Examples
The examples mirror the Rust workspace:
uv run better-result-example basic
uv run better-result-example capture
uv run better-result-example sync-retry
uv run better-result-example async-retry
uv run better-result-example --all
Development
uv sync --all-packages
uv run pytest
uv run pytest --cov
uv run ruff check .
uv run ty check
Metadata
Release files for py-better-result 2.0.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| py_better_result-2.0.1.tar.gz | 7.0 kB | Without provenance | Details for py_better_result-2.0.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| py_better_result-2.0.1-py3-none-any.whl | Python 3 | none | any | Details for py_better_result-2.0.1-py3-none-any.whl |
Total release size: 15.4 kB
Release files / py_better_result-2.0.1.tar.gz
| Download URL | py_better_result-2.0.1.tar.gz |
|---|---|
| Size | 7.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7921f48138d60f3682910f109faae3a0d66b1efbd106c0c4e6754bcca4796526
|
|
BLAKE2b-256 checksum How to use checksums |
7a070473bfcfe4eb42a9a3639a9b699ece7daa903d8140c7ae618ee6eb2b4ccc
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / py_better_result-2.0.1-py3-none-any.whl
| Download URL | py_better_result-2.0.1-py3-none-any.whl |
|---|---|
| Size | 8.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ccbc5538436a250a01be55d2a60dd5d07b64e01e09a7cd119d6bf484532cefdf
|
|
BLAKE2b-256 checksum How to use checksums |
9f9e4d44c071c8f7c722e5e164c226370d9cf48da8aa8e82631b5ead9f5bcf17
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for py-better-result 2.0.1
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.