Skip to content

Instantly share code, notes, and snippets.

@devforfu
Created June 23, 2020 15:16
Show Gist options
  • Save devforfu/0d6b2607d637a180459ef01623e11c73 to your computer and use it in GitHub Desktop.
Save devforfu/0d6b2607d637a180459ef01623e11c73 to your computer and use it in GitHub Desktop.
Error messages
import numpy as np
class MathErrors:
ZeroDivision = 'division failed: argument {argument} is zero.'
NaN = 'multiplication failed: argument {argument} is not a number.'
OutOfRange = 'value {argument} should be in range [{a}, {b}), but {value} received'
def divide(a: float, b: float) -> float:
if b == 0.:
raise ZeroDivisionError(MathErrors.ZeroDivision.format(argument='b'))
return a / b
def multiply(x: float, y: float) -> float:
if np.isnan(x):
raise ValueError(MathErrors.NaN.format(argument='x'))
if np.isnan(y):
raise ValueError(MathErrors.NaN.format(argument='y'))
return x * y
def flip_coin(true_rate: float) -> bool:
lo, hi = 0., 1.
if lo <= true_rate < hi:
return np.random.random() > true_rate
raise ValueError(MathErrors.OutOfRange.format(
argument='true_rate', a=lo, b=hi, value=true_rate))
def main():
faulty_functions = [
(divide, 1, 0),
(multiply, np.nan, 1),
(multiply, 0, np.nan),
(flip_coin, -1)
]
for example in faulty_functions:
function, *args = example
try:
function(*args)
except Exception as e:
print(f'{type(e).__name__}: {e}')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment