Created
March 10, 2022 21:28
-
-
Save lewoudar/b75bf1a846423d76dbb980de84ac7575 to your computer and use it in GitHub Desktop.
An example of function argument validation without using pydantic validate_arguments decorator
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 math | |
from typing import Union | |
def get_hypotenuse(a: Union[int, float], b: Union[int, float]) -> float: | |
if not isinstance(a, (float, int)): | |
raise TypeError | |
if not isinstance(b, (float, int)): | |
raise TypeError | |
# since we are going to square the value the test could just check that the value is 0 | |
# but a user sending a negative value... it is not a good sign | |
# we better have to send him a feedback | |
if a <= 0: | |
raise ValueError | |
if b <= 0: | |
raise ValueError | |
return math.sqrt(a ** 2 + b ** 2) | |
print(get_hypotenuse(1, 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment