Pr0Ger / protobuf3

Protocol buffers library for Python 3
Other
5 stars 5 forks source link

Add a SetInParent equivalent so that is possible to set empty messages as fields of another message #5

Open ecerulm opened 9 years ago

ecerulm commented 9 years ago

for a message like

message ListRequest {
}

message ServerRequest {
   optional ListRequest list = 1;
}

There is no way (that I know of) to conveniently set the list field to be present. In the original protobuf you could

req = mypackage.ServerRequest()
req.list.SetInParent()

to ensure that the list would be included although optional and empty. But there seems that there is no way to do that with protobuf3. Or ?

Pr0Ger commented 9 years ago

As I know empty repeated (or optional) field doesn't have any signs in binary representation, so this call wouldn't affect serialization result

ecerulm commented 9 years ago

It does show up in the binary encoding:

message StartRequest {
}

message StopRequest {
}

message ControlRequest {
  optional StartRequest start = 1;
  optional StopRequest stop = 2;
}

with Python 2.7 protobuf:

import message_pb2 as pb
req = pb.ControlRequest()
req.start.SetInParent()
req.stop.SetInParent()
with open("out.bin", "wb") as f:
    f.write(req.SerializeToString())

the out.bin shows the fields 1 and 2

hexdump -C out.bin
00000000  0a 00 12 00                                       |....|
00000004

and cat out.bin | protoc --decode_raw show that both fields are present:

1: ""
2: ""

if I comment out the req.start.SetInParent() line then I get a different binary of course:

00000000  0a 00                                             |..|
00000002

and protoc --decode_raw show that field start with tag 1 is missing:

2: ""