construct-classes
raw JSON → 0.2.3 verified Mon Apr 27 auth: no python
Parse binary structs defined with the `construct` library into Python dataclasses. Version 0.2.3 requires Python >=3.10, <4.0. Active development.
pip install construct-classes Common errors
error AttributeError: 'MyStruct' object has no attribute 'parse' ↓
cause The class is not decorated with @construct_dataclass, so it lacks the .parse() method.
fix
Add @construct_dataclass above the class definition.
error construct.core.StreamError: could not parse, expected 4 bytes, got 0 ↓
cause Insufficient binary data passed to .parse(). The binary data length is shorter than the struct expects.
fix
Ensure the binary data has enough bytes. For Int32ul, provide at least 4 bytes.
Warnings
gotcha Field order matters: fields must be declared in the same order as in the binary struct. The dataclass field order defines the parse order. ↓
fix Ensure fields are in correct order, e.g., if struct has [Int32ul, Int8ul], declare x first then y.
gotcha Subcon fields: when using subconstructs (e.g., Hex, BytesInteger), you must wrap them correctly. Hex(Int8ul) works, but wrong usage causes cryptic errors. ↓
fix Use construct subcon syntax: field: type = Subcon(InnerSubcon()). For Hex, use Hex(Int8ul).
Imports
- construct_dataclass wrong
from construct_classes import dataclasscorrectfrom construct_classes import construct_dataclass - Struct wrong
from construct_classes import Structcorrectfrom construct import Struct
Quickstart
from construct import Struct, Int32ul, Hex, Int8ul
from construct_classes import construct_dataclass
@construct_dataclass
class MyStruct:
x: int = Int32ul
y: int = Hex(Int8ul)
# Parse binary data
data = b'\x01\x00\x00\x00\x02'
obj = MyStruct.parse(data)
print(obj.x, obj.y)