Skip to content

Instantly share code, notes, and snippets.

@esoxjem
Last active November 16, 2020 10:58
Show Gist options
  • Save esoxjem/895adb956922a06217e9f9e7ded1cea3 to your computer and use it in GitHub Desktop.
Save esoxjem/895adb956922a06217e9f9e7ded1cea3 to your computer and use it in GitHub Desktop.
Result - represents outcome. Avoid propagating exceptions.
class Result:
"""Represents the outcome/result of an operation. Use instead of propogating exceptions
accross layers. Use exceptions for only exceptional cases.
Attributes
----------
success : bool
A flag that is set to True if the operation was successful, False if
the operation failed.
value : object
The result of the operation if successful, value is None if operation
failed or if the operation has no return value.
error : object
Error detailing why the operation failed, value is None if
operation was successful.
Usage
-----
def handler() -> Result
if response.status_code == 200:
return Result.Success(value="dummy value")
else:
return Result.Error(error="dummy error")
def caller():
result = handler()
if result:
print(f"Success: {result.value}")
else:
print(f"Error: {result.error}")
"""
def __init__(self, success, value, error):
self.success = success
self.error = error
self.value = value
def __bool__(self):
return self.success
@classmethod
def Error(cls, error=None):
return cls(False, value=None, error=error)
@classmethod
def Success(cls, value=None):
return cls(True, value=value, error=None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment