Dataclass-Like Serialization Helpers for More Complex Data-Types
Project description
PyStructs
Implements a dataclass version of python's stdlib struct library.
Structs decode values as defined by their type annotations and allows for simple, easy, and fast encoding/decoding of complex data-structures.
Installation
pip install pystructs3
Examples
Simple Example
from pystructs import *
class Foo(Struct):
x: U8
y: U16
z: U32
# same as struct.pack('>BHI', 230, 6500, 2147483648)
foo = Foo(230, 65000, 2147483648)
print(foo)
print(foo.pack())
encoded = pack((U8, U16), 230, 65000)
print(encoded)
decoded = unpack((U8, U16), encoded)
print(decoded)
More Complex Example
from pystructs import *
from typing_extensions import Annotated
class Foo(Struct):
x: I16
y: U32
ip: IPv4
data: Annotated[bytes, SizedBytes[U16]]
class Bar(Struct):
mac: MacAddr
ip6: IPv6
data: Annotated[bytes, StaticBytes[16]]
# use context to encode/decode items in series
ctx = Context()
foo = Foo(69, 420, '1.2.3.4', b'example message')
bar = Bar('00:01:02:03:04:05', '::1', b'message two')
print(foo, bar)
print(foo.x)
raw = foo.encode(ctx) + bar.encode(ctx)
print(raw)
# reset context before switching between encoding/decoding
ctx.reset()
foo2 = Foo.decode(ctx, raw)
bar2 = Bar.decode(ctx, raw)
print(foo2, bar2)
ctx.reset()
encoded = encode(ctx, (I16, IPv4), 1, '1.2.3.4') + \
encode(ctx, (U32, IPv6), 2, '::1')
ctx.reset()
item1 = decode(ctx, (I16, IPv4), encoded)
item2 = decode(ctx, (U32, IPv6), encoded)
print(item1, item2)
Limitations
This implementation is intentionally simple and avoids doing things like allowing hierarchies of structured-objects or any real dynamic behavior outside of parsing a series of specified simple data-types. This is to avoid any complex class definitions that often feel overly esoteric and work like magic. Instead, dynamic parsing is left to standard python code to make things simpler and easier to read.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file pystructs3-0.0.7.tar.gz
.
File metadata
- Download URL: pystructs3-0.0.7.tar.gz
- Upload date:
- Size: 13.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.8.3
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | ef756f1eb10421a8a0666b12bd609a42c8c3488804d09ff7095f378c7139b70a |
|
MD5 | d2f47c6230a2ce2fff259a9e609232a1 |
|
BLAKE2b-256 | 485dc4c7c38efa6662df80e78e194ccde0dac09344a101dc1f49c3479f49c655 |