Struct

Struct

class pystructs.struct.Struct(_raw: bytes | None = None, **kwargs: Any)[source]

Bases: object

Base class for binary structures.

Define fields as class attributes and use parse() to create instances from binary data, or to_bytes() to serialize instances.

Example:
>>> class Packet(Struct):
...     class Meta:
...         endian = 'big'
...     magic = UInt32(default=0xDEADBEEF)
...     version = UInt8(default=1)
...     length = UInt16()
...
>>> packet = Packet.parse(raw_bytes)
>>> packet.version
1
>>> packet.to_bytes()
b'...'
classmethod get_fixed_size() int | None[source]

Get the fixed size of this struct if all fields are fixed-size.

Returns:

Total size in bytes, or None if size is variable

get_size() int[source]

Calculate the current serialization size.

Returns:

Size in bytes

classmethod parse(data: bytes, allow_trailing: bool = False) T[source]

Parse binary data into a struct instance.

Args:

data: Binary data to parse allow_trailing: If True, ignore trailing bytes after parsing

Returns:

Parsed struct instance

Raises:

ParseError: If parsing fails TrailingDataError: If trailing data exists and not allowed

sync(fields: List[str] | None = None) Struct[source]

Run synchronization rules to update field values.

Args:

fields: Specific fields to sync (default: all)

Returns:

self (for method chaining)

to_bytes(sync: bool = False, validate: bool = False) bytes[source]

Serialize the struct to bytes.

Args:

sync: If True, run sync() before serializing validate: If True, run validate() before serializing

Returns:

Serialized bytes

Raises:

SerializationError: If serialization fails ValidationError: If validation fails (when validate=True)

to_dict() Dict[str, Any][source]

Convert to a dictionary.

Returns:

Dictionary with field names as keys

validate() Struct[source]

Run all validation rules.

Returns:

self (for method chaining)

Raises:

ValidationErrors: If any validation fails

StructMeta

class pystructs.struct.StructMeta(name: str, bases: tuple, namespace: dict, **kwargs: Any)[source]

Bases: type

Metaclass for Struct classes.

Responsible for: - Collecting field definitions from class attributes - Preserving field declaration order - Processing the inner Meta class - Validating field types

StructOptions

class pystructs.struct.StructOptions(endian: str = 'little', trailing_data: str = 'error', sync_rules: List[Any] = <factory>, validators: List[Any] = <factory>)[source]

Bases: object

Configuration options for a Struct class.

These are set via the inner Meta class.

endian: str = 'little'
inherit_from(parent: StructOptions) None[source]

Inherit options from a parent Struct.

Args:

parent: Parent struct’s options

sync_rules: List[Any]
trailing_data: str = 'error'
validators: List[Any]