Codecs
Custom codecs and the built-in codec primitives
A codec separates a field’s Python representation from its binary storage. Subclass Codec[PyT, StorageT], set storage to the binary type used on the wire, and implement encode (Python value to storage value) and decode (storage value to Python value). Both take the value and the evaluation scope, positionally. Codec errors are wrapped in EncodeError / DecodeError with the original exception as __cause__.
from typing import Annotated
from binal import BinaryModel, Codec, EvalScope, Int16, UInt32
class Celsius(Codec[float, int]):
storage = Int16
def encode(self, value: float, scope: EvalScope, /) -> int:
return round(value * 100)
def decode(self, value: int, scope: EvalScope, /) -> float:
return value / 100
class Reading(BinaryModel, byte_order="big"):
id: UInt32
temperature: Annotated[float, Celsius()] A codec is always used as an instance (Celsius()); a bare class in the metadata is a SchemaError. storage may also be set per instance in __init__, for a codec whose width is a parameter.
The scope is a read-only mapping of the fields before this one plus the context fields, the same scope When predicates and computed lengths receive. A codec that depends on a context field reads it as scope["base"].
A codec’s storage width and length come from the storage annotation’s own markers when it has them, and otherwise are inherited from the field — so Annotated[str, UpperCodec(), Prefixed(UInt8)] (bytes storage) and Annotated[int, RaisingCodec(), UInt8] (int storage, width from the field) both work. An int-storage codec requires an integer type on the field or on the storage annotation. A codec’s storage must be self-delimiting: bytes or str storage needs Sized, Padded, Prefixed, or NullTerminated. Constraints on the storage type are checked on the storage value when encoding and decoding.
Codec primitives
The built-in types are Annotated aliases pairing a Python type with a binary representation:
Integer(bits, signed=False, byte_order=None)— integer metadata of any width:Annotated[int, Integer(24)].UInt8…Int128are aliases of it.Float(format, byte_order=None)— binary floating point;Float16,BFloat16,Float8E4M3, …Float128are aliases of it.Bool8— a boolean as one byte, 0 or 1.VarInt(kind, zigzag=False, bits=None)— variable-length integers;ULEB128,SLEB128,ZigZag32,ZigZag64,ZigZag, andVLQare aliases of it.
The built-in semantic types — UUID, IPv4, Timestamp, FixedPoint, DecimalFloat, BCD, Rational, and the rest — are codecs too, documented under Binary Types.
from typing import Annotated
from binal import BinaryModel, Float32, Integer
class CustomWidth(BinaryModel, byte_order="big"):
a: Annotated[int, Integer(24)]
b: Float32
c: Annotated[int, Integer(12, signed=True)] The varint rules, including the acceptance of non-canonical encodings on decode, are in the Integers page.