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.
pip install construct-typingVerified import paths — ran on the pinned version, not inferred.
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.
Update `pyright` to a compatible version (e.g., `v1.1.310` or newer) and review type checking errors, adjusting code if necessary to align with the new stub definitions.
Always pass an instance of the associated `dataclass` when building with `DataclassStruct` and related typed constructs. The `dataclass` instance ensures type correctness at build time.
Exercise caution when relying on advanced features of `construct_typed` in production. Monitor release notes for potential breaking changes. Consider pinning to specific `construct-typing` versions to mitigate unexpected updates.
Choose a primary type checker and configure it strictly (e.g., `pyright` is often preferred by `construct-typing` for its `__new__` handling). If supporting both, be aware of potential differences and consult each tool's documentation for specific configurations or known limitations related to complex typing.
Install the 'construct-typing' package using pip: `pip install construct-typing`
Import the specialized typed constructs from the `construct_typed` module: `from construct_typed import DataclassStruct, TEnum`
Ensure that the `construct-typing` package is correctly installed in the Python environment being used by the type checker. Running `pip install construct-typing` should resolve this by installing `construct-stubs`.
To achieve strongly-typed structures with proper autocompletion and type validation, use `DataclassStruct` from `construct_typed` in conjunction with a Python `dataclass` to define the structure and its fields with explicit type annotations.