Validation
Constraints and structured errors
from typing import Annotated
from binal import BinaryModel, MaxLength, Prefixed, Range, UInt16
class Packet(BinaryModel, byte_order="big"):
port: Annotated[UInt16, Range(1, 65535)]
payload: Annotated[bytes, Prefixed(UInt16), MaxLength(4096)] Invalid values raise ValidationError with the field path, the expected constraint, and the received value. Truncated or trailing data raises DecodeError with the byte offset, expected size, and available size.
When validation runs
Validation runs at construction, at the end of decoding, and at the start of encode() — before any byte is written. The same checks run in each place, in the same order:
- Field types: strict, no silent coercion — an
intfield takes anint, not abool,float, orstr. - Field constraints, including collection elements and custom codecs.
- Nested models, depth-first.
- Derived-field consistency (lengths, counts, checksums, offsets).
- The model-level
__binal_validate__hook, last.
On decode, checksum verification happens before model validation. A field whose When condition is false is absent on the wire and is not validated.
Encode revalidates
encode() revalidates the instance before writing anything, so a model mutated into an invalid state after construction cannot produce invalid bytes. A failed encode() writes nothing.
from binal import BinaryModel, UInt8, ValidationError
class Interval(BinaryModel, byte_order="big"):
start: UInt8
end: UInt8
def __binal_validate__(self) -> None:
if self.start > self.end:
raise ValidationError("start must be <= end", path="Interval")
interval = Interval(start=10, end=20)
interval.end = 5
interval.encode() # ValidationError: start must be <= end Structured errors
Errors carry the field path and the relevant details, so failures are actionable instead of bare messages. ValidationError carries path, expected, received, and offset (the byte offset when it is known). DecodeError carries path, offset, expected, available, received, and reason; is_incomplete marks an error that means the input ended mid-field, and claimed is the byte count the failing read needed. Streaming code branches on is_incomplete, never on the reason string.