Types & Refinements (Where)

Every declared type in a specification gives the set of values a name may take.

Supported Types#

Python TypeDomain / ValuesNeeds Entry in Model.domains?
int, strUnbounded integers, stringsYes (when quantified over)
boolTrue, FalseNo (inherently finite)
None, T | None, Optional[T]None, or domain of T plus NoneOnly for T
Literal["a", "b"], EnumExactly the declared valuesNo (inherently finite)
tuple[T, ...], list[T]Finite sequencesYes (when quantified over)
frozenset[T], set[T]Finite setsYes (when quantified over)
dict[K, V]Finite mappingsYes (when quantified over)
ModelValue subclassOpaque, distinct identities (TLA⁺ model values)Yes
TypeVarAbstract type parameter values given by the modelYes

Refined Types with Where#

Annotated[T, Where(predicate, "description")] represents the set comprehension {x ∈ T : predicate(x)}. Multiple Where annotations on the same type are conjoined.

python
from typing import Annotated
from temporal_typing import Where

Positive = Annotated[int, Where(lambda x: x > 0, "positive")]
NonNegative = Annotated[int, Where(lambda x: x >= 0, "non-negative")]
SortedInts = Annotated[
    tuple[int, ...],
    Where(lambda xs: all(xs[i] <= xs[i + 1] for i in range(len(xs) - 1)), "sorted"),
]

Define a refined type once — where it is placed determines what obligation it creates:

PositionObligationTLA⁺ Equivalent
c: Constant[Positive]Model assumptionASSUME p(c)
v: State[NonNegative] or Ghost[...]State invariant□p(v)
Action or contract parameter x: PositiveGuard / domain filterOnly values where p(x) holds are taken
Action or contract return typePostcondition on resultp(result) must hold on every return

Python Meaning, Not TLA⁺ Quirks#

Where Python and TLA⁺ disagree, Python's semantics win:

  • Integer division // floors toward -∞; modulo % takes the sign of the divisor (-7 % 3 == 2, 7 % -3 == -2). Float division / is rejected as unsupported.
  • Sequences are indexed from 0 and support negative indexing (xs[-1]) and slices (xs[1:]).
  • and and or short-circuit and return an operand; empty collections are falsy.
  • Runtime errors (out-of-range index, missing dictionary key, division by zero, failed assert) are failures of the specification, not undefined values.