Construct Typing

0.7.0 · active · verified Sun Apr 12

Construct Typing is an extension for the `construct` Python package, which provides a powerful declarative and symmetrical parser and builder for binary data. It enhances `construct` by adding comprehensive typing features, including `.pyi` stub files for the entire `construct` library (via `construct-stubs`) and additional strongly-typed classes (via `construct_typed`) for improved autocompletion and type hints, particularly for complex structures like `Struct` and `Enum`. The library is actively maintained, with regular releases, and the latest version is 0.7.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a typed binary structure using `construct-typing`'s `DataclassStruct` and `TEnum`. It shows how to combine standard `construct` fields with Python dataclasses, enabling strong type hints for both parsing and building binary data. The example includes parsing existing binary data into a typed object and building binary data from a typed object, highlighting the symmetric nature of `construct` augmented with type safety.

import dataclasses
import typing as t
from construct import Array, Byte, Const, Int8ub, this
from construct_typed import DataclassMixin, DataclassStruct, TEnum, csfield

# Define a typed Enum
class Orientation(TEnum, Int8ub):
    HORIZONTAL: t.ClassVar[int] = 0
    VERTICAL: t.ClassVar[int] = 1

# Define a typed Struct using dataclasses
@dataclasses.dataclass
class Image(DataclassMixin):
    signature: bytes = csfield(Const(b"BMP"))
    orientation: Orientation = csfield(TEnum(Int8ub, Orientation))
    width: int = csfield(Int8ub)
    height: int = csfield(Int8ub)
    pixels: t.List[int] = csfield(Array(this.width * this.height, Byte))

# Example usage: Parse binary data
img_bytes = b"BMP\x00\x03\x02\x07\x08\t\x0b\x0c\r"
parsed_image = Image.parse(img_bytes)
print(f"Parsed Image: {parsed_image}")
# Expected: Parsed Image: Image(signature=b'BMP', orientation=<Orientation.HORIZONTAL: 0>, width=3, height=2, pixels=[7, 8, 9, 11, 12, 13])

# Example usage: Build binary data from a typed object
built_bytes = Image.build(
    Image(
        orientation=Orientation.HORIZONTAL,
        width=3,
        height=2,
        pixels=[7, 8, 9, 11, 12, 13]
    )
)
print(f"Built Bytes: {built_bytes}")
# Expected: Built Bytes: b'BMP\x00\x03\x02\x07\x08\t\x0b\x0c\r'

view raw JSON →