Search code examples
pythonprotocol-buffers

Protobuf doesn't serialize default values


I'm using Protobuf for python.

I've been trying to use default values but everytime I run SerializeToString() i get nothing.

For example,

here is my .proto file object

message Test{

    optional string lol = 1 [default="HI"];
    optional int32 num = 2 [default=200];
}

I run

test = packets_pb2.Test()
print(test.num)
print(test.SerializeToString())

and get 200 for print(test.num) but no results (empty) for SerializeToString()

I want my default values to be serialized.

Any idea how to get this done?

Thanks in advance.


Solution

  • This is working as intended. Default values are not sent on the wire. Instead, the receiving end assumes that if a field isn't present, then it should use the default value. This saves space on the wire by not sending common values. This does mean that the client and server have to agree on the default values; you generally should not change the default values in your .proto files.

    Keep in mind that the main purpose of default values is to be able to handle messages from old clients that were built before the field existed. So, those clients clearly can't send the default value on the wire since they don't know anything about it.