Constraints
Value constraints checked at construction and decode
Constraints are used inside Annotated metadata. They are checked when an instance is constructed, when data is decoded, and at the start of encode(); a violation raises ValidationError with the field path, the expected constraint, and the received value. A field whose When condition is false is not validated.
Range
Range(minimum, maximum) requires a numeric value to lie within [minimum, maximum] (inclusive).
MaxLength / MinLength
MaxLength(n) requires len(value) <= n; MinLength(n) requires len(value) >= n. They apply to bytes, str, and lists. A value with no length fails the check.
Pattern
Pattern(r"[A-Za-z]+") requires the whole string to match a regular expression (re.fullmatch).
Custom
Custom(predicate, description) requires a value to satisfy a user-supplied predicate. The description names the constraint in the error message; it defaults to the predicate’s __name__.
from typing import Annotated
from binal import (
BinaryModel,
Custom,
MaxLength,
MinLength,
Pattern,
Prefixed,
Range,
UInt8,
UInt16,
)
class Packet(BinaryModel, byte_order="big"):
port: Annotated[UInt16, Range(1, 65535)]
name: Annotated[
str,
Prefixed(UInt8),
MinLength(1),
MaxLength(10),
Pattern(r"[A-Za-z]+"),
]
tag: Annotated[UInt8, Custom(lambda v: v % 2 == 0, "even number")]
Packet(port=80, name="abc", tag=4) # OK
Packet(port=0, name="abc", tag=4) # ValidationError: port out of range
Packet(port=80, name="abc123", tag=4) # ValidationError: name does not match
Packet(port=80, name="abc", tag=3) # ValidationError: tag is not even Constraints compose: several markers on one field are all checked, in the order written.