Created
March 14, 2019 11:12
-
-
Save leohowell/e328a7166f60d9196519fbf6ec12247e to your computer and use it in GitHub Desktop.
Rust Result for Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import traceback | |
class CallableResult: | |
class NoneResult: | |
pass | |
NONE = NoneResult | |
def __init__(self): | |
self.value = self.NONE | |
self.exception = None | |
self.traceback = None | |
def __call__(self, func): | |
def wrapper(*args, **kwargs): | |
try: | |
self.value = func(*args, **kwargs) | |
except Exception as err: | |
self.exception = err | |
contents = traceback.format_exception(*sys.exc_info()) | |
self.traceback = ''.join(contents) | |
return self | |
return wrapper | |
def __bool__(self): | |
return self.value != self.NONE | |
def Result(func): | |
return CallableResult()(func) | |
@Result | |
def foo(): | |
raise ValueError("error in foo") | |
@Result | |
def bar(x, y): | |
return x + y | |
result1 = foo() | |
if not result1: | |
# do something | |
print(result1.traceback) | |
else: | |
print(result1.value) | |
result2 = bar(2, 5) | |
if not result2: | |
# do something | |
print(result2.traceback) | |
else: | |
print(result2.value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment