Dynamic Fields
Lengths, counts, conditions, and unions
Derived lengths are computed automatically:
from typing import Annotated
from binal import BinaryModel, LengthOf, Sized, UInt16
class Packet(BinaryModel, byte_order="big"):
length: Annotated[UInt16, LengthOf("payload")]
payload: Annotated[bytes, Sized("length")]
packet = Packet(payload=b"Hello")
packet.length # 5
packet.encode() # b'\x00\x05Hello' CountOf is the same idea for the element count of a list, paired with Array(count="n"). See Field Markers for the full list of length, count, and framing markers.
Conditional fields
When includes a field only when a condition holds. The field-equality form names an earlier field; the predicate form takes a callable over the already-decoded values, which is how multi-field, compound, and custom conditions are written — in plain Python, with no separate expression language. A field whose condition is false is absent on the wire.
from typing import Annotated
from binal import BinaryModel, UInt8, UInt16, When
class Maybe(BinaryModel, byte_order="big"):
has_extra: UInt8
extra: Annotated[UInt16, When("has_extra", equals=1)]
total: UInt8
class Compound(BinaryModel, byte_order="big"):
a: UInt8
b: UInt8
c: Annotated[UInt16, When(lambda v: v["a"] == 1 and v["b"] == 2)]
Maybe(has_extra=1, extra=7, total=3).encode() # b'\x01\x00\x07\x03'
Maybe(has_extra=0, total=3).encode() # b'\x00\x03' Constant fields
Const(value) is a constant field for any type — int, float, bool, bytes, str, or enum. The field is derived (no constructor argument): the encoder writes the constant and the decoder verifies it.
from typing import Annotated
from binal import BinaryModel, Const, Prefixed, UInt8, UInt16
class File(BinaryModel, byte_order="big"):
magic: Annotated[bytes, Const(b"BINA")]
version: Annotated[UInt8, Const(1)]
body: Annotated[bytes, Prefixed(UInt16)]
File(body=b"data").encode() # b'BINA\x01\x00\x04data' Offsets
Offset("payload") on an integer field makes it a pointer to another field: its value is the byte position of the target, measured from the start of the model (base="start") or from the offset field’s own position (base="self"). On decode the target is read from the recorded offset, so data that lives elsewhere in the input still decodes.
from typing import Annotated
from binal import BinaryModel, Offset, Prefixed, UInt16
class Packet(BinaryModel, byte_order="big"):
off: Annotated[UInt16, Offset("payload")]
payload: Annotated[bytes, Prefixed(UInt16)]
Packet(payload=b"AB").encode() # b'\x00\x02\x00\x02AB' Per-field byte order
ByteOrder("little") overrides the model’s byte order for one field. It applies to int, float, enum, and nested-model fields, and is the unified spelling for what IntegerCodec(byte_order=...) also does.
from typing import Annotated
from binal import BinaryModel, ByteOrder, UInt16, UInt32
class Mixed(BinaryModel, byte_order="big"):
a: UInt16
b: Annotated[UInt32, ByteOrder("little")]
Mixed(a=1, b=2).encode() # b'\x00\x01\x02\x00\x00\x00' Discriminated unions
TaggedUnion selects the variant model from the value of a discriminator field of the containing model.
from typing import Annotated
from binal import BinaryModel, TaggedUnion, UInt8, UInt16
class Circle(BinaryModel, byte_order="big"):
radius: UInt16
class Square(BinaryModel, byte_order="big"):
side: UInt16
class Shape(BinaryModel, byte_order="big"):
kind: UInt8
shape: Annotated[
Circle | Square,
TaggedUnion(discriminator="kind", variants={1: Circle, 2: Square}),
]
Shape(kind=2, shape=Square(side=5)).encode() # b'\x02\x00\x05' Model-level validation
A model may define __binal_validate__(self) to check invariants spanning several fields. It runs after construction and after decode, and raises ValidationError. See Schema and Layout and Validation.
from binal import BinaryModel, UInt8, ValidationError
class Range(BinaryModel, byte_order="big"):
lo: UInt8
hi: UInt8
def __binal_validate__(self) -> None:
if self.lo > self.hi:
raise ValidationError("lo must be <= hi", path="Range")
Range(lo=5, hi=2) # ValidationError The full reference for every marker is in Field Markers; checksums are in Checksums, constraints in Constraints, and custom codecs in Custom Codecs.