Skip to Content
Binal
API Reference

Constraints

Value constraints checked at construction and decode

Constraints are used inside Annotated metadata. They are checked when an instance is constructed and when data is decoded; 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 a string value to match a regular expression. The match is a search (re.search), not a full match — anchor the pattern with ^ and $ when the whole string must match.

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.