Field Markers
The Annotated markers that shape a field's binary form
Field markers are used inside Annotated metadata. They say how a field is framed, whether it is present, and what value it carries. Each marker is listed with the field kind it applies to.
Lengths and sizes
LengthOf / CountOf / Sized
LengthOf("payload") on an integer field makes it derived: its value is the length of the named field’s current value, computed on every access and written on encode. CountOf("items") is the same for the element count of a list. Sized("length") on a bytes or str field reads its size from an earlier integer field.
from dataclasses import field
from typing import Annotated
from binal import Array, BinaryModel, CountOf, LengthOf, Sized, UInt8, UInt16
class Packet(BinaryModel, byte_order="big"):
length: Annotated[UInt16, LengthOf("payload")] = field(init=False)
payload: Annotated[bytes, Sized("length")]
class Batch(BinaryModel, byte_order="big"):
n: Annotated[UInt8, CountOf("items")] = field(init=False)
items: Annotated[list[UInt16], Array(count="n")]
packet = Packet(payload=b"Hello")
packet.length # 5
packet.encode() # b'\x00\x05Hello' Derived fields take no constructor argument and cannot be assigned. A length that does not fit its integer type fails at encode, with ValidationError.
Sized also accepts a literal size (Sized(4)) and a callable over the evaluation scope (Sized(lambda scope: scope["length"] - 4)). The computed size is validated before any byte is read or written, and fixed_size() is None when any expression is present.
Sized (or an Array(count="n")) whose length field was skipped by a When condition reads to the end of the input instead, when it is the last field.
Framing
Prefixed
Prefixed(UInt16) writes a length prefix using the given integer type (any integer type, or a varint type), followed by the field data. For strings, encoding selects the text encoding. The prefix uses its own byte order, not a ByteOrder marker on the field.
from typing import Annotated
from binal import BinaryModel, Prefixed, UInt16
class Message(BinaryModel, byte_order="big"):
text: Annotated[str, Prefixed(UInt16, encoding="utf-8")] Sized
Sized(n) is an exact-length field: the value is always exactly n bytes. On decode, an exact bytes field returns all n bytes as-is (trailing zeros are data, not padding), and an exact string decodes all n bytes with no NUL splitting or stripping. On encode, a value whose length is not exactly n raises ValidationError – a short value is never silently padded. The length may also be a field name (Sized("length")) or a callable over the evaluation scope.
from typing import Annotated
from binal import BinaryModel, Sized
class Record(BinaryModel, byte_order="big"):
tag: Annotated[bytes, Sized(4)]
Record(tag=b"AB\x00\x00").encode() # b'AB\x00\x00'
Record.decode(b"AB\x00\x00").tag # b'AB\x00\x00' Padded
Padded(n, pad=b"\x00", strip=True) is a fixed-length field with explicit padding: encode pads a short value with pad (repeated to fill the field) and decode strips trailing pad bytes when strip is True, preserving them when it is False. For strings with the default NUL pad, decode splits at the first NUL and raises if non-zero bytes follow it (UTF-16/32 strings strip trailing NUL characters instead). With strip=True, encoding a value that decoding would not give back unchanged (one that ends with the pad byte, for example) raises ValidationError.
from typing import Annotated
from binal import BinaryModel, Padded
class Record(BinaryModel, byte_order="big"):
tag: Annotated[bytes, Padded(4)]
Record(tag=b"AB").encode() # b'AB\x00\x00'
Record.decode(b"AB\x00\x00").tag # b'AB' NullTerminated
NullTerminated(encoding="utf-8") is a string field terminated by a single NUL byte (a NUL code unit for UTF-16/32). The terminator is consumed on decode and written on encode.
Array
Array(count=16) is a fixed-length collection, Array(count_prefix=UInt16) prefixes the element count, and Array(count="n") reads the count from an earlier field named n. The count may also be a callable over the evaluation scope (Array(count=lambda v: sum(v["mask"]))), validated against the collection size limit before any element is read or written.
from typing import Annotated
from binal import Array, BinaryModel, Float32, UInt16
class SensorData(BinaryModel, byte_order="big"):
samples: Annotated[list[Float32], Array(count_prefix=UInt16)]
class Matrix(BinaryModel, byte_order="big"):
values: Annotated[list[Float32], Array(count=16)] Terminated
Terminated(0xFFFF) on a list field reads elements until one equals the sentinel value. The terminator is consumed but not included in the result, unless include=True. If the input ends without the terminator, decoding fails with DecodeError. On encode, a list without include=True must not contain the sentinel (the encoder appends it); with include=True it must end with the sentinel and contain it nowhere else, so the bytes always decode back to the same list. A callable sentinel is a predicate: reading stops at the first element for which it returns True; the encoder cannot invent such an element, so a predicate requires include=True.
from typing import Annotated
from binal import BinaryModel, Terminated, UInt16
class Words(BinaryModel, byte_order="big"):
words: Annotated[list[UInt16], Terminated(0xFFFF)]
Words(words=[1, 2]).encode() # b'\x00\x01\x00\x02\xff\xff' Greedy
Greedy() on a list field reads elements until the end of the input. The field must be the last field, since nothing can follow a field that consumes the rest of the input. A fixed-size element stops cleanly at padding bits that cannot form another element. On encode the elements are written with no count or terminator. A bytes field with no length mechanism is greedy in the same way.
from typing import Annotated
from binal import BinaryModel, Greedy, UInt8
class Tail(BinaryModel, byte_order="big"):
head: UInt8
rest: Annotated[list[UInt8], Greedy()]
Tail.decode(b"\x09\x01\x02\x03").rest # [1, 2, 3] Constants and layout
Const
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 raises DecodeError on mismatch. An int constant needs an integer type, e.g. Annotated[UInt8, Const(1)]. For bytes/str without a length mechanism, the length is inferred from the constant.
from dataclasses import field
from typing import Annotated
from binal import BinaryModel, Const, Prefixed, UInt8, UInt16
class File(BinaryModel, byte_order="big"):
magic: Annotated[bytes, Const(b"BINA")] = field(init=False)
version: Annotated[UInt8, Const(1)] = field(init=False)
body: Annotated[bytes, Prefixed(UInt16)]
File(body=b"data").encode() # b'BINA\x01\x00\x04data' Padding
Padding(3) is reserved padding of three zero bytes. The bytes are written on encode and validated as zeros on decode.
Align
Align(4) aligns the next field to a multiple of 4 bytes. The alignment is relative to the start of the model, and the pad bytes are validated as zeros on decode. The alignment may also be a field name or a callable over the evaluation scope.
from dataclasses import field
from typing import Annotated
from binal import Align, BinaryModel, Padding, UInt8, UInt32
class Aligned(BinaryModel, byte_order="big"):
a: UInt8
pad: Annotated[bytes, Padding(3)] = field(init=False)
b: Annotated[UInt32, Align(4)]
Aligned(a=1, b=2).encode() # b'\x01\x00\x00\x00\x00\x00\x00\x02' ByteOrder
ByteOrder("little") overrides the model’s byte order for one field. It applies to int, float, enum, and nested-model fields. It is the only per-field spelling. It does not apply to length prefixes — the prefix codec’s own byte order governs those.
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' ByteOrderMark
ByteOrderMark({b"II": "little", b"MM": "big"}) makes the field’s value choose the byte order of every field after it, as the first bytes of a TIFF file or the data byte of an ELF header do. The keys are values of the field: ints, enum members, bytes, or strings. Nested models, union members, and referenced objects after the mark are read in the same order; a ByteOrder marker on a field still overrides it. A value the mapping does not name fails validation and is a DecodeError.
from typing import Annotated
from binal import BinaryModel, ByteOrderMark, Sized, UInt16
class Header(BinaryModel):
order: Annotated[bytes, Sized(2), ByteOrderMark({b"II": "little", b"MM": "big"})]
magic: UInt16
Header(order=b"II", magic=42).encode() # b'II*\x00'
Header(order=b"MM", magic=42).encode() # b'MM\x00*' The mark is an unconditional field. A type whose byte order Python applies itself (a storage word of a BitModel, an integer wider than 128 bits, a float format the runtime does not implement) needs its own ByteOrder after a mark.
Pointers
Offset
Offset("payload") on an integer field makes it a pointer: its value is the byte position of the named target field. base="start" (default) measures from the start of the model; base="self" measures from the offset field’s own position. The field is derived (no constructor argument; reading it encodes the instance to find the position) and must be declared before its target. The target must not be a bit field and must not be conditional; the offset field itself must not be conditional. The offset value points at the target field’s start — for a Prefixed target, that includes its length prefix.
On decode, the target is read from the recorded offset and the reader position is restored, so data that lives elsewhere in the input (a gap, an out-of-order section) 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".
from dataclasses import field
from typing import Annotated
from binal import BinaryModel, Offset, Prefixed, UInt16
class Packet(BinaryModel, byte_order="big"):
off: Annotated[UInt16, Offset("payload")] = field(init=False)
payload: Annotated[bytes, Prefixed(UInt16)]
Packet(payload=b"AB").encode() # b'\x00\x02\x00\x02AB'
# The payload lives at offset 8, after a 6-byte gap:
Packet.decode(b"\x00\x08\x00\x00\x00\x00\x00\x00\x00\x02AB").payload # b'AB' Conditions and unions
When
When("has_extra", equals=1) includes the field only when the named field equals the given value. When(predicate) takes a callable receiving the evaluation scope — the already-decoded values plus context, a mapping (not a dict), so values["flag"] and values.get("flag") keep working — and the field is present when its result is truthy. This is how multi-field, compound, and custom conditions are written, in plain Python, with no separate expression language. A predicate may only read fields declared before the conditional field. A conditional field is annotated X | None: it is None exactly when its condition is false, and a value given while the condition is false raises ValidationError rather than being silently dropped. A size or count that comes from a conditional field needs the same When.
from typing import Annotated
from binal import BinaryModel, UInt8, UInt16, When
class Maybe(BinaryModel, byte_order="big"):
has_extra: UInt8
extra: Annotated[UInt16 | None, When("has_extra", equals=1)]
total: UInt8
class Compound(BinaryModel, byte_order="big"):
a: UInt8
b: UInt8
c: Annotated[UInt16 | None, 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, extra=None, total=3).encode() # b'\x00\x03'
Compound(a=1, b=2, c=9).encode() # b'\x01\x02\x00\x09' TaggedUnion
TaggedUnion(discriminator="kind", variants={1: Circle, 2: Square}) selects the variant model from the value of the discriminator field. The discriminator must be a field of the containing model, read from already-decoded values — not a field of the variants. For a recursive union, quote the whole annotation so the variant classes are looked up at first use.
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' EnumField
EnumField(UInt8, on_unknown="raise") is an enumeration field backed by an integer type. on_unknown controls decoding of values not in the enum: "raise" (default) raises a decode error, "keep" keeps the raw integer value, so the field must be annotated Enum | int. Without "keep" only enum members are valid values; with it, raw integers in range are accepted too.
from enum import IntEnum
from typing import Annotated
from binal import BinaryModel, EnumField, UInt8
class Color(IntEnum):
RED = 1
GREEN = 2
class Pixel(BinaryModel, byte_order="big"):
color: Annotated[Color | int, EnumField(UInt8, on_unknown="keep")]
Pixel(color=Color.RED).encode() # b'\x01'
Pixel.decode(b"\x07").color # 7 Context
Context
Context() on a field declares it as external context: it takes a constructor argument, occupies zero bytes on the wire, and is not derived. When decoding, its value is supplied as context={...}; a missing required context field, an unknown key, or a wrongly typed value raises ValidationError before any byte is read. Encoding reads the value from the instance and takes no context. A context field is required unless it has a class-level default.
Context is passed down the nesting tree; a nested model may declare its own context fields, satisfied from the same context by name. Precedence for one nested context field: a value in the context mapping beats a value inherited from the enclosing model’s values, which beats the field’s default. The mapping lives for exactly one decode call, with no global or thread-local state.
from enum import IntFlag
from typing import Annotated
from binal import BinaryModel, Context, Sized, UInt8, When
class RecordFlags(IntFlag):
HAS_PAYLOAD = 1
class Record(BinaryModel):
flags: Annotated[RecordFlags, Context()]
kind: UInt8
payload: Annotated[
bytes | None,
When(lambda values: values["flags"] & RecordFlags.HAS_PAYLOAD),
Sized(4),
]
Record.decode(b"\x01abcd", context={"flags": RecordFlags.HAS_PAYLOAD})
Record.decode(b"\x01", context={"flags": RecordFlags(0)})
Record.decode(b"\x01abcd") # ValidationError: Missing required context field 'flags' Context is visible to When predicates, computed expressions, LengthOf / CountOf targets, validators (as self.<field>), and codecs (through their scope argument).
Args
Args(size="length") passes arguments to the typed parameters of a nested model, a list element model, or a Ref target. The model declares its parameters as a class argument, params={"size": int}, with the types int, bool, bytes, or str, and its fields read them by name like earlier fields. An argument is the name of an earlier field or of the enclosing model’s own parameter, an int, bool, or bytes literal, or a callable of the evaluation scope; every parameter needs one. Names and literals are portable schema; a callable is a host part.
from typing import Annotated
from binal import Args, BinaryModel, Sized, UInt16
class Chunk(BinaryModel, params={"size": int}):
body: Annotated[bytes, Sized("size")]
class File(BinaryModel):
length: UInt16
chunk: Annotated[Chunk, Args(size="length")]
File(length=3, chunk=Chunk(b"xyz")).encode() # b'\x00\x03xyz' A parameter is not a field: the decoded Chunk holds only body. A model with parameters is decoded and encoded as a field of a model that passes them; on its own, decode and encode raise SchemaError. Prefer parameters over context fields when a value only flows from a parent to a child.
Bit fields
Bits
Bits(3) is a bit field of 3 bits, for use in BitModel. int bit fields are unsigned by default (range 0 .. 2**width-1); pass signed=True for a two’s-complement field (range -2**(width-1) .. 2**(width-1)-1), which sign-extends on decode. The width may also be a field name or a callable over the evaluation scope. Bit arrays — list[Annotated[int, Bits(3)]] — pack elements across byte boundaries.
from typing import Annotated
from binal import Array, BitModel, Bits
class Flags(BitModel, bit_order="msb"):
version: Annotated[int, Bits(3)]
delta: Annotated[int, Bits(3, signed=True)]
flag: Annotated[bool, Bits(1)]
class Samples(BitModel, bit_order="msb"):
values: Annotated[list[Annotated[int, Bits(3)]], Array(4)]