Created
October 16, 2018 17:05
-
-
Save JBirdVegas/a37619415d30361805f8fac2d8dfd621 to your computer and use it in GitHub Desktop.
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 typing | |
def safer_execute(method: typing.Callable[[typing.Any, typing.Optional[typing.Dict[str, typing.Any]]], typing.Any], | |
errors: typing.List[typing.Type[Exception]], | |
*args, default=None, **kwargs): | |
try: | |
return method(*args, **kwargs) | |
except tuple(errors): | |
if callable(default): | |
return default(*args, **kwargs) | |
return default | |
conversion_errors = [ | |
# value could not be converted to a float | |
ValueError, | |
# value was zero | |
ZeroDivisionError, | |
# value was None | |
# TypeError | |
] | |
def div(count, total): | |
return (float(count) / float(total)) * 100 | |
if __name__ == '__main__': | |
a = safer_execute(div, conversion_errors, 'not a float', 1, default=0) | |
print(f"A: {a:.0f} %") | |
b = safer_execute(div, conversion_errors, 12, 0) | |
print(f"B: {b}") | |
c = safer_execute(div, conversion_errors, 2, 10, default=0) | |
print(f"C: {c:.0f} %") | |
# note we are not catching the `TypeError` so it will trigger an exception | |
d = safer_execute(div, conversion_errors, None, None, default=0) | |
print(f"D: {d:.0f} %") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment