Last active
September 6, 2022 11:25
-
-
Save wrenoud/3680863d1ee4644c9aec9e6f8e856a89 to your computer and use it in GitHub Desktop.
dataclass concept extended to support binary serialization/deserialization with numpy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass, astuple | |
import numpy as np | |
def dtypeclass(cls): | |
cls = dataclass(cls) | |
def frombuffer(cls, buffer, offset=0): | |
values = np.frombuffer(buffer, cls._dtype, count=1, offset=offset) | |
return cls(*values[0]) | |
def tobytes(self): | |
return np.array(astuple(self), dtype=self._dtype).tobytes() | |
setattr(cls, "_dtype", np.dtype(list(cls.__annotations__.items()))) | |
setattr(cls, "frombuffer", classmethod(frombuffer)) | |
setattr(cls, "tobytes", tobytes) | |
return cls | |
@dtypeclass | |
class MyClass: | |
b: np.float32 | |
a: np.int16 | |
if __name__ == "__main__": | |
a = MyClass(5.0, 2) | |
print(a.tobytes()) | |
b = MyClass.frombuffer(a.tobytes()) | |
print(b) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
b'\x00\x00\xa0@\x02\x00' | |
MyClass(b=5.0, a=2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This seems like a more modern approach to what I was trying to do with https://github.com/wrenoud/structobject. Especially because the
_field_order
member can be dropped because of the dictionary order guarantee introduced in 3.7.