Last active
March 16, 2021 17:54
-
-
Save julianpistorius/49bd189ee3dd94babd9ef1affc23d9ef to your computer and use it in GitHub Desktop.
Simplistic 'design-by-contract' example in 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
def add(x, y): | |
# Precondition | |
assert isinstance(x, int), 'x is not an integer' | |
assert isinstance(y, int), 'y is not an integer' | |
answer = x + y | |
# Postcondition | |
assert isinstance(answer, int), 'answer is not an integer' | |
return answer | |
things_to_add = [ | |
(2, 3), | |
(2.3, 3.4), | |
(100, '200'), | |
('300', '400') | |
] | |
for x, y in things_to_add: | |
print(f'Going to add {x} and {y}') | |
try: | |
answer = add(x, y) | |
print(f'Answer = {answer}') | |
except Exception as e: | |
print(f'Something went wrong while adding x and y: "{e}"') | |
print('\n--------------------------\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run with assertions turned on
Run with assertions turned off