Skip to content

Instantly share code, notes, and snippets.

@julianpistorius
Last active March 16, 2021 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julianpistorius/49bd189ee3dd94babd9ef1affc23d9ef to your computer and use it in GitHub Desktop.
Save julianpistorius/49bd189ee3dd94babd9ef1affc23d9ef to your computer and use it in GitHub Desktop.
Simplistic 'design-by-contract' example in Python
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')
@julianpistorius
Copy link
Author

julianpistorius commented Mar 16, 2021

Run with assertions turned on

$ python3 design-by-contract.py 
Going to add 2 and 3
Answer = 5

--------------------------

Going to add 2.3 and 3.4
Something went wrong while adding x and y: "x is not an integer"

--------------------------

Going to add 100 and 200
Something went wrong while adding x and y: "y is not an integer"

--------------------------

Going to add 300 and 400
Something went wrong while adding x and y: "x is not an integer"

--------------------------

Run with assertions turned off

$ python3 -O design-by-contract.py 
Going to add 2 and 3
Answer = 5

--------------------------

Going to add 2.3 and 3.4
Answer = 5.699999999999999

--------------------------

Going to add 100 and 200
Something went wrong while adding x and y: "unsupported operand type(s) for +: 'int' and 'str'"

--------------------------

Going to add 300 and 400
Answer = 300400

--------------------------

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment