Skip to Content
Binal

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:

  1. Field types: strict, no silent coercion — an int field takes an int, not a bool, float, or str.
  2. Field constraints, including collection elements and custom codecs.
  3. Nested models, depth-first.
  4. Derived-field consistency (lengths, counts, checksums, offsets).
  5. 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.