A modern library that simplifies packing and unpacking to a whole other level.
Project description
packer.typed
A modern library that simplifies packing and unpacking to a whole other level.
Usage
Basic Usage
from packer import Int8, Pack
from dataclasses import dataclass
@packable
@dataclass
class SimpleStruct:
test1: Pack[Int8]
test2: Pack[Int8]
test = SimpleStruct(1, 2)
test.pack() # \x01\x02
Creating & Using custom types
from packer import TypeDescriptor, packable, Pack, OptionalPack
from dataclasses import dataclass
class LengthPrefixedStr(TypeDescriptor):
__data_size__: int = 2
@classmethod
def pack(cls, val: str) -> bytes:
return int.to_bytes(len((enc := val.encode())), 2, "little") + enc
@classmethod
def unpack(cls, data: bytearray) -> tuple[int, str]:
str_len = int.from_bytes(data[:2], "little")
return str_len + 2, data[2 : 2 + str_len].decode()
@packable
@dataclass
class CustomTypesStruct:
test1: Pack[LengthPrefixedStr]
test2: OptionalPack[LengthPrefixedStr] = None
test = CustomTypesStruct("hi")
test.pack() # b"\x02\x00hi"
test.test2 = "hi2"
test.pack() #b"\x02\x00hi\x03\x00hi2"
Notes
If you're going to use this with a dataclass then be prepared to lose object attr typehints. A simple workaround is to declare object attributes with the types like the following:
@packable
@dataclass
class SimpleStruct:
id: Pack[Int32] = 0
val: OptionalPack[Float] = None
def __post_init__(self) -> None:
self.id: int
self.val: float | None
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
packer_typed-0.1.2.tar.gz
(6.7 kB
view details)
Built Distribution
File details
Details for the file packer_typed-0.1.2.tar.gz
.
File metadata
- Download URL: packer_typed-0.1.2.tar.gz
- Upload date:
- Size: 6.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.6
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 157669b5f7522e370eb9aa3e112142816a755f05edffbd861e0585b80272250f |
|
MD5 | fb02f7e0bc4e0e4123617fc52956e6ff |
|
BLAKE2b-256 | f6c9a1860d7bcc82c9307449fc50ae7f818d49fa51937330aaa9c1859fa409ae |
File details
Details for the file packer.typed-0.1.2-py3-none-any.whl
.
File metadata
- Download URL: packer.typed-0.1.2-py3-none-any.whl
- Upload date:
- Size: 7.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.6
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | b59170b8c92f6ba01a0cdb9351d177b02247307bcd9c484d0e8fc68800c6816f |
|
MD5 | 07c4e933c6ed51e28708606ff67820a2 |
|
BLAKE2b-256 | 6a6cb5e7e4320eb295721a0af48cabe64b528380b328984e017f1ef69821da95 |