Portable Schemas
Export a model's format for other languages and tools
Every model runs on Binal’s one engine as a schema: plain data that
describes the bytes. export_schema returns it in a form any language
can read.
from typing import Annotated
from binal import BinaryModel, Prefixed, Range, UInt8, UInt16, export_schema
class Packet(BinaryModel, byte_order="big"):
version: Annotated[UInt8, Range(1, 3)]
payload: Annotated[bytes, Prefixed(UInt16)]
schema = export_schema(Packet)
schema.root # "Packet": the type that decodes the model
schema.to_json() # versioned JSON, for other languages and tools
schema.to_source() # .binal text struct Packet {
byte_order big,
bit_order msb,
version: u8 where version >= 1 && version <= 3,
payload: bytes prefix u16,
} Constraints the schema can state (Range, MinLength, MaxLength)
become where checks, so the exported schema accepts exactly the data
the model accepts.
What is not portable
Some parts of a model only Python can run. host_parts lists them,
each with the field it is in and a kind:
| Kind | Meaning | Export |
|---|---|---|
conversion | How a value is presented in Python: a uuid.UUID, a codec’s object, a float format the schema lacks. The bytes are its storage type’s. | Keeps the storage type and lists the field in schema.stored. Pass conversions="refuse" to refuse instead. |
function | A Python callable decides a length, a count, a condition, or a computed value. | Refused |
check | A constraint (Custom, Pattern) or __binal_validate__ hook no schema can state. | Refused |
context | A value supplied from Python when decoding. | Refused |
from binal import UUID, NotPortableError, Sized, host_parts
class Record(BinaryModel, byte_order="big"):
ident: UUID
n: UInt8
body: Annotated[bytes, Sized(lambda s: s["n"] * 2)]
for part in host_parts(Record):
print(part)
# Record.ident: the codec UUIDCodec (conversion)
# Record.body: the length is computed by a Python callable (function)
try:
export_schema(Record)
except NotPortableError as exc:
exc.parts # every part that blocks export, all at once To make Record portable, say what the callable says as a field
reference: Sized("n") when the length is stored, or a stored length
field with LengthOf("body").
A schema states its format version. A reader refuses a version it does
not know, so a schema never changes meaning silently. binal check schema.binal on the command line reports whether a schema is portable
and lists its host parts.