External Context
Values supplied from outside the wire
Some binary structures depend on information that is not stored in the structure itself: flags in an index entry, a protocol version set by a parent structure, a file header’s configuration, dimensions decided by the caller. A context field declares that dependency instead of hiding it in a global or a closure.
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(flags=<RecordFlags.HAS_PAYLOAD: 1>, kind=1, payload=b'abcd')
Record.decode(b"\x01", context={"flags": RecordFlags(0)})
# Record(flags=<RecordFlags: 0>, kind=1, payload=None) A missing context field raises ValidationError before any byte is read:
Record.decode(b"\x01abcd") # ValidationError: Missing context value for 'flags' A context field takes a constructor argument, occupies zero bytes on the wire, and is not derived. It is an ordinary instance attribute, so validators read it as self.flags and When predicates read it from the scope like any other field.
Supplying context
Context only exists on the decoding side. It is one flat mapping of field names to values, passed as context={...} to decode, decode_partial, read, iter_read, read_async, iter_read_async, incremental_parser, read_file, BinaryReader.read_model, and BinaryReader.read_at. Encoding takes no context: an instance already holds its context fields’ values, so encode(), write(), write_file(), and write_async() read them from the instance.
record = Record.decode(b"\x01abcd", context={"flags": RecordFlags.HAS_PAYLOAD})
record = Record(flags=RecordFlags.HAS_PAYLOAD, kind=1, payload=b"abcd")
record.encode() # b"\x01abcd" A supplied value is checked against the declared type the same way a constructed value is. A key that names no context field of the model, or of a model nested in it, is a ValidationError, so a misspelt name cannot be silently ignored.
A context field is required like any other field. Allowing None in the annotation does not make it optional; a class-level default does (flags: Annotated[RecordFlags, Context()] = RecordFlags(0)), and the field is then optional in the constructor and when decoding.
Propagation
Context is passed down the nesting tree. A nested model may declare its own context fields, satisfied from the same context by name. It is not passed sideways (sibling fields do not see each other’s context except through the scope) and not passed up (a nested model’s context never mutates the parent’s).
For one nested context field, the precedence is: a value in the context mapping beats a value inherited from the enclosing model’s values (a parent field with the same name), which beats the field’s default.
from typing import Annotated
from binal import BinaryModel, Context, UInt8, UInt16, When
class Inner(BinaryModel):
flags: Annotated[RecordFlags, Context()]
value: Annotated[
UInt16 | None, When(lambda v: v["flags"] & RecordFlags.HAS_PAYLOAD)
]
class Outer(BinaryModel):
flags: Annotated[RecordFlags, Context()]
inner: Inner
tail: UInt8
Outer.decode(b"\x00\x05\x07", context={"flags": RecordFlags.HAS_PAYLOAD})
# Outer(flags=<RecordFlags.HAS_PAYLOAD: 1>,
# inner=Inner(flags=<RecordFlags.HAS_PAYLOAD: 1>, value=5), tail=7) The context mapping lives for exactly one decode call (or, for an incremental parser, for the parser). There is no global or thread-local state anywhere.
Where context is visible
Context is visible everywhere a field’s shape or value can depend on something already known:
Whenpredicates read context fields from the scope like any other field.- Computed expressions (
Sized,Array(count=...),Offset,Align,Paddedlength,Bitswidth) read context from the same scope. LengthOf/CountOftargets may name a context field.- Validators read context fields as instance attributes (
self.flags). - Codecs receive the same scope as their second argument:
scope["flags"].
Parameters
When a value only flows from a parent model to a nested one, a typed parameter states it without context: the nested model declares params={"size": int}, and the parent passes the value with Args(size="length"). Parameters lower to the portable schema’s type parameters, so they stay schema rather than Python; see Args.