Skip to main content

rust-result

More radical approach to Rust's std::result in Python.

Motivation

I do not want exceptions in my code. Rust has this figured out quite neatly by essentially revolving around two pathways for errors: A possible error condition is either one that has no prospect of being handled -- then the program should terminate -- or it is one that could be handled -- then it has to be handled or explicitly ignored.

This concept is replicated here by using AssertionError to emulate Rust's panic!, mapping all unhandled exceptions to AssertionError and providing a Rust-like result type to signal error conditions that do not need to terminate the program.

Documentation

from rust_result import Ok, Err, returns_result

@returns_result()
def read_file():
    with open('/this/path/is/invalid') as f:
        return Ok(f.read())

result = func()

This will raise an AssertionError due to an unhandled exception.

But if you specify the exceptions you expect, you can handle the error:

@returns_result(FileNotFoundError)
def read_file():
    with open('/this/path/is/invalid') as f:
        return Ok(f.read())

result = func()
if result.is_ok():
    print(f'File content: {result.unwrap()}')
else:
    print(f'Error: {result.unwrap_err()}')

Or -- if you are feeling fancy -- you can do pattern matching:

@returns_result(FileNotFoundError)
def read_file():
    with open('/this/path/is/invalid') as f:
        return f.read()

result = read_file()
match result:
    case Ok(v):
        print(f'File content: {v}')
    case Err(e):
        print(f'Error: {e}')

And even fancier:

data = [
    { 'foo': 'value-1' },
    { 'bar': 'value-2' }
]

@returns_result(IndexError, KeyError)
def retrieve_record_entry_backend(index, key):
    return Ok(data[index][key])

def retrieve_record_entry(index, key):
    match retrieve_record_entry_backend(index, key):
        case Ok(v):
            print(f'Retrieved: {v}')
        case Err(IndexError()):
            print(f'No such record: {index}')
        case Err(KeyError()):
            print(f'No entry `{key}` in record {index}')

retrieve_record_entry(2, 'foo')    # No such record: 2
retrieve_record_entry(1, 'foo')    # No entry `foo` in record 1
retrieve_record_entry(1, 'bar')    # Retrieved: value-2

Similar Projects

For a less extreme approach on Rust's result type, see:

Metadata

Release files for rust-result 0.2.1

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

Source distribution (sdist)

Source distribution for rust-result 0.2.1
File Size Uploaded
rust_result-0.2.1.tar.gz 3.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for rust-result 0.2.1
File Interpreter ABI Platform
rust_result-0.2.1-py3-none-any.whl Python 3 none any Details

Total release size: 7.1 kB

Release files / rust_result-0.2.1.tar.gz

Download URL rust_result-0.2.1.tar.gz
Size 3.2 kB
Tags Source
SHA-256 checksum
How to use checksums
db91371538ae870a4d552ce59e6c3deba9110094ee8bcd6a46dce44464d1c11b
BLAKE2b-256 checksum
How to use checksums
2f552593c81761ba46186bfa5828031a5e47eeb59a17492825f7ec10bc8ead0a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.3 CPython/3.10.12 Linux/5.15.0-113-generic

Release files / rust_result-0.2.1-py3-none-any.whl

Download URL rust_result-0.2.1-py3-none-any.whl
Size 3.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0d428de9f54c0fe512631e150201b5165bf08f9128ca35c5de2c3ac96436c422
BLAKE2b-256 checksum
How to use checksums
1430af630ee6f06c34b6b40b2966173dca8c011b09449e8adefe9c97ce2340a5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.3 CPython/3.10.12 Linux/5.15.0-113-generic

Release history Release notifications | RSS feed

This release

0.2.1 This release

2 release files

0.2.0

2 release files

0.1.0

2 release files

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