Consider the Construct library: https://construct.readthedocs.io/en/latest/
Similar but different to Protobuf, it allows you to define a "packed" data format, which is ideal when dealing with packed data formats, such as network packets or proprietary data formats.
from construct import Struct, Int16ub, Int32ub
# Your data format
my_packet_struct = Struct(
"field1" / Int16ub,
"field2" / Int16ub,
"field3" / Int32ub
)
# Some data you want serialise.
# The dict keys need to match those in the packet format above,
# but not necessarily the same order
my_data = {
"field2": 321,
"field1": 123,
"field3": 999
}
# Serialise your data to bytes
my_serialised_bytes = my_packet_struct.build(my_data)
print("Serialised Bytes: {}".format(my_serialised_bytes.hex()))
# Send the data: socket.write(my_serialised_bytes)
# Deserialise to prove it works properly
my_deserialised_bytes = my_packet_struct.parse(my_serialised_bytes)
print("\nDeserialised object:")
print(my_deserialised_bytes)
Output:
Serialised Bytes: 007b0141000003e7
Deserialised object:
Container:
field1 = 123
field2 = 321
field3 = 999