Types & Refinements (Where)
Every declared type in a specification gives the set of values a name may take.
Supported Types#
| Python Type | Domain / Values | Needs Entry in Model.domains? |
|---|---|---|
int, str | Unbounded integers, strings | Yes (when quantified over) |
bool | True, False | No (inherently finite) |
None, T | None, Optional[T] | None, or domain of T plus None | Only for T |
Literal["a", "b"], Enum | Exactly the declared values | No (inherently finite) |
tuple[T, ...], list[T] | Finite sequences | Yes (when quantified over) |
frozenset[T], set[T] | Finite sets | Yes (when quantified over) |
dict[K, V] | Finite mappings | Yes (when quantified over) |
ModelValue subclass | Opaque, distinct identities (TLA⁺ model values) | Yes |
TypeVar | Abstract type parameter values given by the model | Yes |
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:
| Position | Obligation | TLA⁺ Equivalent |
|---|---|---|
c: Constant[Positive] | Model assumption | ASSUME p(c) |
v: State[NonNegative] or Ghost[...] | State invariant | □p(v) |
Action or contract parameter x: Positive | Guard / domain filter | Only values where p(x) holds are taken |
| Action or contract return type | Postcondition on result | p(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 asunsupported. - Sequences are indexed from
0and support negative indexing (xs[-1]) and slices (xs[1:]). andandorshort-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.