Function Contracts

A module-level function whose return annotation carries Requires or Ensures is a function contract. You don't need a class or @spec to verify algorithmic helpers.

contracts.py
from typing import Annotated
from temporal_typing import Ensures, Model, Pure, Requires, Where, implies

NonNegative = Annotated[int, Where(lambda x: x >= 0, "non-negative")]


def clamp(value: int, low: int, high: int) -> Annotated[
    Pure[int],
    Requires(lambda low, high: low <= high, "a non-empty interval"),
    Ensures(lambda value, low, high, result: low <= result <= high and implies(low <= value <= high, result == value)),
]:
    if value < low:
        return low
    if value > high:
        return high
    return value


clamp_model = Model(clamp, domains={int: range(-3, 4)})

What a Checker Verifies#

For every argument tuple in the model's domains where every Requires and every parameter Where holds, the checker verifies that:

  1. The function body returns normally (no uncaught raise, failed assert, IndexError, or ZeroDivisionError).
  2. The returned value satisfies every Ensures clause and any Where on the return type.

Contract predicates bind parameters by name (with result in Ensures) and have no state parameter s. As in methods, predicates may omit parameters they do not reference.

Contracts Over Collections#

Give finite collections in domains to test algorithms like binary search over edge cases (empty tuples, singletons, duplicates, negatives):

python
SortedInts = Annotated[
    tuple[int, ...],
    Where(lambda xs: all(xs[i] <= xs[i + 1] for i in range(len(xs) - 1)), "sorted"),
]

def binary_search(xs: SortedInts, target: int) -> Annotated[
    Pure[NonNegative | None],
    Ensures(lambda xs, target, result: (result is None and target not in xs) or (result is not None and xs[result] == target)),
]:
    lo, hi = 0, len(xs) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if xs[mid] == target:
            return mid
        if xs[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return None

search_model = Model(
    binary_search,
    domains={
        SortedInts: [(), (1,), (1, 3), (1, 3, 5), (2, 2, 4), (-1, 0, 0, 7)],
        int: range(-2, 8),
    },
)
Bounded verification

A contract's PASS verdict holds for the finite domains supplied in its Model — always choose domains that exercise boundary cases (empty sequences, zero, negative values, duplicates).