Skip to content

Instantly share code, notes, and snippets.

@JBirdVegas
Created October 16, 2018 17:05
Show Gist options
  • Save JBirdVegas/a37619415d30361805f8fac2d8dfd621 to your computer and use it in GitHub Desktop.
Save JBirdVegas/a37619415d30361805f8fac2d8dfd621 to your computer and use it in GitHub Desktop.
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