Dynamic Fields
Lengths, counts, conditions, and unions
Derived lengths are computed automatically:
from dataclasses import field
from typing import Annotated
from binal import BinaryModel, LengthOf, Sized, UInt16
class Packet(BinaryModel, byte_order="big"):
length: Annotated[UInt16, LengthOf("payload")] = field(init=False)
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").
Computed sizes, counts, and offsets
A size, count, offset, bit width, or alignment may be a literal, a field name, or a plain Python callable over the evaluation scope — the values decoded (or constructed) so far, in declaration order, plus context. Sized, Array(count=...), Offset, Align, Padded length, and Bits width all accept int | str | Callable[[EvalScope], int], and When predicates are unified onto the same scope. There is no separate expression language.
from typing import Annotated
from binal import BinaryModel, Sized, UInt8, UInt16
class Bitmap(BinaryModel, byte_order="little"):
width: UInt16
height: UInt16
bits_per_pixel: UInt8
# Each row is padded to a multiple of four bytes.
pixels: Annotated[
bytes,
Sized(lambda v: (v["width"] * v["bits_per_pixel"] + 31) // 32 * 4 * v["height"]),
]
Bitmap(width=3, height=2, bits_per_pixel=24, pixels=bytes(24)).encoded_size() # 29 Evaluation order is declaration order: an expression may only read fields declared before the field that uses it, plus context fields (available from the start). The computed value is validated before anything acts on it: it must be a non-negative int (rejecting bool, float, str, None) and satisfy the resource limits (max_collection_size for counts, max_field_length for lengths) before allocation or looping. A computed count that disagrees with the list length on encode raises ValidationError. A computed offset is verified against the wire on decode and the target’s actual position on encode.
A callable may declare what it reads via a depends_on attribute, so the compiler checks the reference at class definition; cycles among derived and computed values are rejected with the cycle path. Without the hint, reading a missing key raises a structured error naming the field, never a bare KeyError. A computed size is dynamic: fixed_size() is None when any expression is present.
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 evaluation scope — decoded values so far plus context — 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 Connect(BinaryModel, byte_order="big"):
version: UInt8
has_keepalive: UInt8
keepalive: Annotated[UInt16 | None, When("has_keepalive", equals=1)]
# Sessions were added in version 5.
session: Annotated[
UInt16 | None, When(lambda v: v["version"] >= 5 and v["has_keepalive"] == 1)
] = None
Connect(version=5, has_keepalive=1, keepalive=60, session=7).encode()
# b'\x05\x01\x00\x3c\x00\x07'
Connect(version=4, has_keepalive=0, keepalive=None).encode() # b'\x04\x00' 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 dataclasses import field
from typing import Annotated
from binal import BinaryModel, Const, Prefixed, UInt8, UInt16
class Snapshot(BinaryModel, byte_order="big"):
magic: Annotated[bytes, Const(b"SNAP")] = field(init=False)
version: Annotated[UInt8, Const(1)] = field(init=False)
body: Annotated[bytes, Prefixed(UInt16)]
Snapshot(body=b"data").encode() # b'SNAP\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. The target may also be computed: Offset(16) is a fixed byte position, and Offset(lambda scope: ...) computes the position from the evaluation scope; with a computed target the field it points at is the field declared immediately after the offset field, and base must be "start". A backward target — pointing at bytes the sequential reader already passed — decodes, and the reader continues from the sequential position afterwards.
from dataclasses import field
from typing import Annotated
from binal import BinaryModel, Offset, Prefixed, UInt16
class Firmware(BinaryModel, byte_order="big"):
code_offset: Annotated[UInt16, Offset("code")] = field(init=False)
vendor: Annotated[str, Prefixed(UInt16)]
code: Annotated[bytes, Prefixed(UInt16)]
Firmware(vendor="ACME", code=b"\x90\x90").code_offset # 8 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 only per-field spelling.
from typing import Annotated
from binal import BinaryModel, ByteOrder, UInt16, UInt32
class CaptureRecord(BinaryModel, byte_order="big"):
length: UInt16
timestamp: Annotated[UInt32, ByteOrder("little")]
CaptureRecord(length=1, timestamp=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, IPv4, Prefixed, TaggedUnion, UInt8, UInt16
class ConnectTo(BinaryModel, byte_order="big"):
address: IPv4
port: UInt16
class Send(BinaryModel, byte_order="big"):
data: Annotated[bytes, Prefixed(UInt16)]
class Command(BinaryModel, byte_order="big"):
kind: UInt8
body: Annotated[
ConnectTo | Send,
TaggedUnion(discriminator="kind", variants={1: ConnectTo, 2: Send}),
]
Command(kind=2, body=Send(b"hi")).encode() # b'\x02\x00\x02hi'
match Command.decode(bytes.fromhex("01 c0a80001 01bb")).body:
case ConnectTo(address=address, port=port):
print(address, port) # 192.168.0.1 443
case Send(data=data):
print(len(data)) A union without TaggedUnion is untagged: decoding tries the member models in declaration order and keeps the first that decodes, rewinding after each failure, and raises DecodeError with the last member’s error when none does. Encoding writes the member the value is an instance of. Order the members from the most to the least specific, since a permissive member listed first wins. On a stream whose length is not yet known, running out of input propagates instead of trying the next member.
from typing import Annotated
from binal import BinaryModel, Sized, UInt8
class Data(BinaryModel, byte_order="big"):
length: UInt8
payload: Annotated[bytes, Sized("length")]
class Ping(BinaryModel, byte_order="big"):
code: UInt8
class Frame(BinaryModel, byte_order="big"):
body: Data | Ping
Frame.decode(b"\x02ab").body # Data(length=2, payload=b'ab')
Frame.decode(b"\x05").body # Ping(code=5): Data needs 5 more bytes A model can refer to itself, directly or through a list, to describe a recursive structure such as a tree; Limits.max_nesting_depth bounds how deep decoding goes.
Model-level validation
A model may define __binal_validate__(self) to check invariants spanning several fields. It runs after construction, after decode, and at the start of encode() — before any byte is written — and raises ValidationError. A model mutated into an invalid state after construction can no longer be encoded: a failed encode() writes nothing.
from binal import BinaryModel, UInt16, ValidationError
class PortRange(BinaryModel, byte_order="big"):
first: UInt16
last: UInt16
def __binal_validate__(self) -> None:
if self.first > self.last:
raise ValidationError("first must be <= last", path="PortRange")
PortRange(first=8080, last=80) # ValidationError