Tribler/py-ipv8

Can the dataclass wrapper use custom packers?

bacox opened this issue · 2 comments

When adding custom packers for specific types this works fine when you call the serialization yourself.
The dataclass wrapper has some additional type checking on the attributes that throws errors before you can run the serialization (On creation of the dataclass).

If I define a custom packer for a community:

class MyCommunity(Community):

    def get_serializer(self) -> Serializer:
        serializer = super().get_serializer()
        serializer.add_packer('json', PackerJSON())
        return serializer

Can I use this to automatically serialize json properties in messages?
I know the check done in payload_dataclass.py#L20 is static, but could there be a way to extend the type checking of the payload_dataclass dynamically?

I know fix_pack_<field> exists (#1251) but adding that to every message feels like a lot of duplicate code.
Ideally I would define a packer for a specific type and hook that to the dataclass.

I'm using:
Py-IPv8 v2.12.2003
Python 3.9.5

Please tell me if you need further info.

Yes, you can! Based on your packer name (PackerJSON), I assume you are working from the example in serialization_5.py. You can modify the example Message to be a dataclass instead of a VariablePayload, as follows:

from ipv8.messaging.payload_dataclass import dataclass, type_from_format

@dataclass(msg_id=1)
class Message:
    d1: type_from_format("json")
    d2: type_from_format("json")
    d3: type_from_format("json")
    d4: type_from_format("json")

I assume and hope your question has been sufficiently answered and I'll close this issue. Please reopen this issue or create a new one if you have other questions.