Skip to content

Instantly share code, notes, and snippets.

@Alexhuszagh
Last active February 16, 2020 20:58
Show Gist options
  • Save Alexhuszagh/1cfc82e2b4d0efe92954126305697166 to your computer and use it in GitHub Desktop.
Save Alexhuszagh/1cfc82e2b4d0efe92954126305697166 to your computer and use it in GitHub Desktop.
Rust-style Result for Python
'''
result
------
Rust-style results and decorator for Python.
Note: I don't personally advocate using it in production, but it's a much better
option than using the following:
https://twitter.com/DinisCruz/status/1229058078714351616
License
-------
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
'''
import functools
# Used to differentiate `None` values from errors.
class _NONE_TYPE:
__slots__ = ()
NONE = _NONE_TYPE()
def to_result(function):
'''try/except a block and return a Result type instead.'''
@functools.wraps(function)
def wrapper(*args, **kwds):
try:
return Result.from_ok(function(*args, **kwds))
except Exception as err:
return Result.from_err(err)
return wrapper
class Result:
'''Rust-like result class'''
def __init__(self, value=NONE, error=NONE):
value_none = value is NONE
error_none = error is NONE
if not (value_none ^ error_none):
raise RuntimeError('Result must have either a value or an error, but not both.')
self.value = value
self.error = error
def __repr__(self):
if self.is_ok:
return f'Result(value={repr(self.value)})'
return f'Result(error={repr(self.error)})'
@classmethod
def from_ok(cls, value):
'''Create result from value.'''
return cls(value=value)
@classmethod
def from_err(cls, error):
'''Create result from error.'''
return cls(error=error)
@property
def is_ok(self):
'''Get if result contains a value.'''
return self.value is not NONE
@property
def is_err(self):
'''Get if result contains an error.'''
return self.error is not NONE
def and_then(self, function):
'''
Apply function to result value if result is ok.
Function should return a Result.
.. code-block:: python
@to_result
def maybe_square(x):
if x > 50:
raise ValueError('Value is too high')
return x * 5
result = Result.from_ok(5)
result.and_then(maybe_square) # Result(value=25)
'''
if self.is_ok:
return function(self.value)
return self
def map(self, function):
'''
Apply function to result value if result is ok.
Function should return a value.
.. code-block:: python
def square(x):
return x * x
result = Result.from_ok(5)
result.map(square) # Result(value=25)
'''
cls = self.__class__
if self.is_ok:
return cls.from_ok(function(self.value))
return self
def map_or(self, default, function):
'''
Apply function to result value if result is ok, or return the default
which is a value.
.. code-block:: python
def square(x):
return x * x
result = Result.from_ok(5)
result.map_or(0, square) # Result(value=25)
'''
if self.is_ok:
return function(self.value)
return default
def map_or_else(self, default, function):
'''
Apply function to result value if result is ok, or return the default
which is a callback.
.. code-block:: python
def square(x):
return x * x
def square_error(error):
return 0
result = Result.from_ok(5)
result.map_or(square_error, square) # Result(value=25)
'''
if self.is_ok:
return function(self.value)
return default(self.error)
def unwrap(self):
'''
Unwraps the value.
Re-raises the exception if the value contains an error.
'''
if self.is_err:
raise self.error
return self.value
def unwrap_or(self, default):
'''
Unwraps the value, or return a default value.
'''
if self.is_err:
return default
return self.value
def unwrap_or_else(self, default):
'''
Unwraps the value, or return a default from a callback.
'''
if self.is_err:
return default(self.error)
return self.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment