01 / 20

Function Contracts
& Invariants

Learn to state clear input/output contracts and invariants for Python functions: the promises your code makes and keeps.

Python

What is a Function Contract?

A function contract is a precise agreement between the function and its caller. It specifies two things: what the function requires from the caller (inputs), and what it guarantees in return (outputs).

Precondition
What must be true before the function runs: valid types, value ranges, non-empty collections.
Postcondition
What is guaranteed after the function finishes: return type, value constraints, side effects.

The Contract Pipeline

PRECONDITION Input requirements must be satisfied FUNCTION Processes input Maintains invariants Produces output POSTCONDITION Output guarantees are delivered Invariant holds throughout

Why Contracts Matter

Without contracts, functions become black boxes with hidden assumptions. Contracts make those assumptions explicit, preventing bugs before they happen.

Bug Prevention
Catch invalid inputs at the boundary instead of deep inside nested logic.
Documentation
Contracts serve as living docs: anyone reading the function instantly knows how to use it.
Testability
Each contract clause maps directly to a unit test: if preconditions are met, postconditions must hold.

Formal Definitions

1
Precondition: A boolean expression that must be True when the function is called. If violated, the caller is at fault.
2
Postcondition: A boolean expression that must be True when the function returns. If violated, the function is at fault.
3
Invariant: A boolean expression that must remain True before, during, and after the function executes: a property that never changes.

Anatomy of a Contract in Python

1 2 3 4 5 6 7 8 9 10 11 12 def average ( nums : list [ float ]) -> float : """
Pre: nums is non-empty, all elements numeric
Post: returns the arithmetic mean
Inv: nums is not modified
""" assert len ( nums ) > 0 total = sum ( nums ) result = total / len ( nums ) assert isinstance ( result , float ) return result Precondition Postcondition Invariant assert (Pre) assert (Post)

Preconditions vs Postconditions

Precondition Postcondition
When checked Before execution After execution
Who is responsible Caller Function
If violated Caller's bug Function's bug
Python tool assert at start assert before return
Example \( n > 0 \) \( \text{result} \geq 0 \)

Understanding Invariants

An invariant is a condition that stays true throughout a function's execution. While preconditions and postconditions are checked at the boundaries, invariants describe properties that never change no matter what happens inside.

Data Invariant
A data structure maintains its shape: a sorted list stays sorted, a tree stays balanced.
Loop Invariant
A property that holds before and after every iteration of a loop.
No-Mutation Invariant
The function does not modify its input arguments: the original data is preserved.

How to Write a Contract

1
Identify the inputs. List every parameter, its type, and any constraints on its value (e.g., must be positive, non-empty, within range).
2
State preconditions. Write each constraint as a boolean expression. These become your assert statements or docstring clauses.
3
Identify the output. Determine the return type and any guarantees about the returned value's properties.
4
State postconditions. Express what must be true about the return value. Add assert before the return.
5
Identify invariants. Determine what must remain unchanged: input data, data structure properties, or loop conditions.

Example 1: Square Root

def safe_sqrt(x: float) -> float: """ Pre: \( x \geq 0 \) Post: \( \text{result} \geq 0 \) Post: \( |\text{result}^2 - x| < 10^{-9} \) Inv: x is not modified """ assert x >= 0, "x must be non-negative" result = x ** 0.5 assert result >= 0 return result

Example 2: Binary Search

def binary_search(arr: list[int], target: int) -> int: """ Pre: arr is sorted in ascending order Pre: all elements in arr are int Post: returns index i where arr[i] == target Post: returns -1 if target not in arr Inv: arr is never modified Inv: target is always in \( \text{arr}[\text{lo}..\text{hi}] \) (if present) """ lo, hi = 0, len(arr) - 1 while lo <= hi: mid = (lo + hi) // 2 if arr[mid] == target: return mid elif arr[mid] < target: lo = mid + 1 else: hi = mid - 1 return -1

Example 3: Withdraw from Account

def withdraw(balance: float, amount: float) -> float: """ Pre: \( \text{balance} \geq 0 \) Pre: \( \text{amount} > 0 \) Pre: \( \text{amount} \leq \text{balance} \) Post: \( \text{result} = \text{balance} - \text{amount} \) Post: \( \text{result} \geq 0 \) Inv: total money is conserved """ assert balance >= 0 assert 0 < amount <= balance result = balance - amount assert result >= 0 return result

Loop Invariants Explained

Initialization Invariant holds? ✓ Condition true? Yes Loop body (preserves invariant) No Invariant + !condition = Postcondition ✓

Common Mistakes

✕ Too Weak Preconditions
Forgetting to check for empty lists or negative values. The function crashes deep inside instead of at the boundary.
✕ Confusing Pre and Post
Mixing up whose responsibility it is. The caller ensures preconditions; the function ensures postconditions.
✕ Mutating Inputs Silently
Modifying a list or dict argument without stating it in the contract. The caller's data changes without warning.
✕ Vague Invariants
Writing "the list stays correct" instead of a precise, testable condition like "\(\text{arr}[0..i]\) is sorted".

Summary Table

Precondition Postcondition Invariant
What it says "Input must be X" "Output will be Y" "Property Z always holds"
Where in code Top of function Before return Throughout body
Python tool assert, type hint assert, type hint Docstring, design
Blame on violation Caller Function Function
Example \(\text{len(arr)} > 0\) \(\text{result} \geq 0\) arr unchanged

Question 1 of 5

A function requires that its input list is non-empty. This requirement is a:

Question 2 of 5

Who is at fault if a postcondition is violated?

Question 3 of 5

Which of the following calls violates the contract?

Question 4 of 5

In a binary search function, the statement "if the target exists, it lies within \(\text{arr}[\text{lo}..\text{hi}]\)" is best described as a:

Question 5 of 5

Which invariant would best complement this contract?