Declarative binary records and composable codecs, using only the standard library
Maintained. Last release 6 weeks ago, commits in 2 of the last 26 weeks. Weaker on commit activity and contributor spread.
pip install bytestruct
bytestruct
bytestruct parses and builds binary wire formats with the standard library alone. Fixed-size records are
dataclasses whose field annotations give each field's wire type; variable-length data is described by small
codecs that compose like construct's. Everything is fully typed.
The layout of a record is compiled into struct.Struct objects once, when the class is defined, so parsing a
record is a single unpack_from per byte-order run.
Documentation: https://doronz88.github.io/bytestruct/, including a migration guide from construct.
Install
python3 -m pip install -U bytestruct
Fixed-size records
from dataclasses import dataclass, field
from enum import IntEnum
from typing import Annotated
from bytestruct import BinaryStruct, Const, PaddedString, u16, u32
class Kind(IntEnum):
FILE = 1
DIRECTORY = 2
@dataclass
class Header(BinaryStruct, byte_order="<"):
magic: Annotated[u32, Const(0x1F3D5B79)] = field(default=0x1F3D5B79, init=False)
size: u32
name: Annotated[str, PaddedString(16)]
kind: Annotated[Kind, u16] # parsed into the enum type
data = Header(size=1024, name="notes.txt", kind=Kind.FILE).build() # a bad value -> BinaryBuildError
header = Header.parse(data) # short input -> TruncatedDataError, wrong magic -> UnexpectedConstantError
assert header.kind is Kind.FILE
Wire fields are positional __init__ parameters in wire order. A field declared
= field(default=..., init=False) is left out of : parse skips its bytes (padding) and build packs
its default (on a field, the constant). Fields without a wire type may follow the wire fields and are
ignored by parse/build. Records cannot be subclassed.