Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 603
Tay Yi Avatar asked Jun 24 '15 08:06

Tay Yi


1 Answers

For anyone using Protobuf 3, there is a way to serialize the default values using the including_default_value_fields argument of MessageToDict or MessageToJson:

from google.protobuf.json_format import MessageToJson

serialized_message_with_defaults = MessageToJson(
    protobuf_instance,
    including_default_value_fields=True,  # this does it
)
like image 100
Franey Avatar answered Sep 30 '22 19:09

Franey