Skip to main content

Boost your `dataclass` objects with suport for binary serialization.

Project description

structclasses

This is a library for working with binary data protocols. Building upon dataclasses from the Python standard library, as well as taking inspiration for the API design from the Ruby gem bindata.

The result is a augmented dataclass object with to/from binary serialization capabilities.

install

pip install structclasses

example

from structclasses import structclass, uint8, union, text, binary


@structclass
class DemoHeader:
  example_id: int  # alias for `int32`


@structclass
class Demo:
  field_a: uint8
  header: DemoHeader
  msg: text[32]     # The length may reference a previously defined field for dynamic length objects.
  payload: union[
    'field_a',      # The value of the named field specifies the union type to use. (May be a callable instead for more flexibility.)
    (0, uint8),     # When `field_a` is 0, `payload` is a `uint8`.
    (1, binary[8])  # When `field_a` is 1, `payload` is a `binary[8]`.
  ]

demo = Demo(field_a=0, msg="hello world", header=DemoHeader(123), payload=42)

packed_binary = demo._pack()  # => b'\x00\x00\x00\x00{hello world\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00*'
Demo._unpack(packed_binary) == demo  # => True

A structclass works as a drop-in substitute for the dataclass decorator, only adding the _pack()/_unpack() methods to the class for serializing to/from binary data.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

structclasses-0.6-py3-none-any.whl (12.8 kB view details)

Uploaded Python 3

File details

Details for the file structclasses-0.6-py3-none-any.whl.

File metadata

  • Download URL: structclasses-0.6-py3-none-any.whl
  • Upload date:
  • Size: 12.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.13

File hashes

Hashes for structclasses-0.6-py3-none-any.whl
Algorithm Hash digest
SHA256 09e0f31e5d52631fcc0de321c41c776c3049e62b452f6d2ed77e9278f736be32
MD5 e67729ac28c062557dde39524cbe58e3
BLAKE2b-256 d1b9f9ff965d1f2a258aac4fc4bfb37b1063dfe48cb9a45c38e77bf30a53bdc2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page