Skip to Content
Binal

Schema Introspection

Inspect fields, sizes, and offsets

from typing import Annotated

from binal import BinaryModel, Prefixed, UInt8, UInt16, UInt32


class Packet(BinaryModel, byte_order="big"):
    version: UInt8
    sequence: UInt32
    payload: Annotated[bytes, Prefixed(UInt16)]


schema = Packet.schema()
for item in schema.fields:
    print(item.name, item.offset, item.size)
# version 0 1
# sequence 1 4
# payload 5 None
schema.fixed_size  # None: the payload has no fixed size

packet = Packet(version=1, sequence=7, payload=b"hi")
packet.encoded_size()  # 9
for placed in packet.layout().fields:
    print(placed.name, placed.byte_offset, placed.byte_size)
# version 0 1
# sequence 1 4
# payload 5 4

fixed_size() returns the total size in bytes for fixed-size models, or None for dynamic models — including any model with a computed expression (a callable size, count, offset, or width). Field offsets are available when all preceding fields have a known fixed size.

schema() reports bit_offset / bit_size per field. layout() reports the logical bit count in total_bits next to total_bytes.