Skip to main content

A rust-like result type for Python

Project description

Resultify

This is an opinionated, simplified fork of dbrgn/result.

Result is a simple, type annotated Result type for Python 3.8+ inspired by Rust.

The idea is that a result value can be either Ok(value) or Err(error), with a way to differentiate between the two. Ok and Err are both classes wrapping an arbitrary value. Result[T, E] is a generic type alias for typing.Union[Ok[T], Err[E]].

Requires Python 3.8 or higher!

Caveats

Not all methods have been implemented, only the ones that make sense in the Python context. For example, the map methods have been omitted, because they don't quite make sense without Rust's pattern matching.

Since Rust's Optional type does not meaningfully translate to Python in a way type checkers are able to understand, ok() corresponds to unwrap() and err() corresponds to unwrap_err(). On the other side, you don't have to return semantically unclear tuples anymore.

By using .is_ok() and is_err() to check for Ok or Err you get type safe access to the contained value. All of this in a package allowing easier handling of values that can be OK or not, without resorting to custom exceptions.

API

Creating an instance:

>>> from resultify import Ok, Err
>>> ok = Ok('yay')
>>> res2 = Err('nay')

Type safe checking whether a result is Ok or Err.

>>> res = Ok('yay')
>>> res.is_ok()
True
>>> res.is_err()
False

Unwrap a Result, or raise if trying to extract a result from an error from a result or vice-versa:

>>> ok = Ok('yay')
>>> err = Err('nay')
>>> ok.ok()
'yay'
>>> ok.err()
resultify.UnwrapError: Cannot unwrap error from Ok: Ok('yay')
>>> err.err()
'nay'
>>> err.ok()
resultify.UnwrapError: Cannot unwrap value from Err: Err('nay')

For your convenience, and to appease the type checkers, simply creating an Ok result without value is the same as using True:

>>> ok = Ok()
>>> ok.ok()
True

To easily convert a function to return Result, you can use resultify():

>>> from resultify import resultify
>>> @resultify()
... def a():
...     return "value"
...
>>> a()
Ok('value')

You can similarly auto-capture exceptions using resultify(...). Please note that you can provide multiple exceptions, or none if you don't want to catch the exception! This is primarily useful when modeling code paths with a single good branch and multiple early raises, where one does not have to concern oneself with annoying try ... catch ... statements.

>>> @resultify(TypeError)
... def foo():
...     raise TypeError()
...
>>> foo()
Err(TypeError())

You can retry a function that returns a Result type with a constant backoff.

>>> from resultify import resultify, retry
... @retry(retries=2, delay=2, initial_delay=1):
... @resultify(Exception)
... def foo():
...     # do something that needs retrying here

This example waits 1 second before executing the initial call, then attempts the initial call, then executes two retries, spaces out two seconds from the previous call. If any execution was a success, the Ok value will be returned. If the retries were exhausted and no Ok was returned, we return the Err value.

For those running Python 3.10, you can make use of Python's structural pattern matching like this:

>>> from resultify import Ok, Err
>>> ok = Ok("ok!")
>>> match ok:
...     case Ok(foo): print(f"Yay {foo}")
...     case Err(foo): print(f"Nay {foo}")
...
Yay ok!
>>> no = Err("nope!")
>>> match no:
...     case Ok(foo): print(f"Yay {foo}")
...     case Err(foo): print(f"Nay {foo}")
...
Nay nope!

Since documentation always lies, please refer to the unit tests for examples of usage.

License

MIT License

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

resultify-1.2.0.tar.gz (5.1 kB view details)

Uploaded Source

Built Distribution

resultify-1.2.0-py3-none-any.whl (5.1 kB view details)

Uploaded Python 3

File details

Details for the file resultify-1.2.0.tar.gz.

File metadata

  • Download URL: resultify-1.2.0.tar.gz
  • Upload date:
  • Size: 5.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.12

File hashes

Hashes for resultify-1.2.0.tar.gz
Algorithm Hash digest
SHA256 47ca1b31212565d2af84e9b227da2ac104e8aae7af2c19e5988ec3b81a7378db
MD5 66590914a6b212db420c1566d142a31e
BLAKE2b-256 8ecd635580a623a2eb44b6d3497b092e0340ccc86b21824e5fbf088279b0940a

See more details on using hashes here.

File details

Details for the file resultify-1.2.0-py3-none-any.whl.

File metadata

  • Download URL: resultify-1.2.0-py3-none-any.whl
  • Upload date:
  • Size: 5.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.12

File hashes

Hashes for resultify-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e31fae10f6462300eb93457b4d97e7e520c2a1eb4f792d1e41e6c7a8e1909816
MD5 30b9045d9eb9cb249bdb80d13e415765
BLAKE2b-256 4b34207de6d0ee01c83171c6f15cfcf5071ab8c7279cd55d0fe61fe659b6b5fa

See more details on using hashes here.

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