Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primitive wrappers in Python for Protobuf

I'm using proto3 and have a message in some .proto file defined as:

message Response {
  google.protobuf.BoolValue field = 1;
  ...
}

In order to initialize Response in Python, I need to create a boolean primitive wrapper and attach some value.

If I were to initialize this value to True, this is fine. From a Python notebook:

In [52]: from google.protobuf import wrappers_pb2 as wrappers
         boo = wrappers.BoolValue(value=True)
         boo

Out [52]: value: true

If I were to initialize this value to False, no wrapped object is created:

In [52]: from google.protobuf import wrappers_pb2 as wrappers
         boo = wrappers.BoolValue(value=False)
         boo

Out [52]: 

How can create a BoolValue initialized to false?

like image 635
Rohan Aletty Avatar asked Jun 29 '17 22:06

Rohan Aletty


1 Answers

Non-truthy values are removed from the fields list as implemented here.

>> boo = wrappers.BoolValue(value=True)
>> boo.ListFields()
[(<google.protobuf.descriptor.FieldDescriptor object at 0x10a037bd0>, True)]

>> boo = wrappers.BoolValue(value=False)
>> boo.ListFields()
[]

In order to access the message value you can write it like this:

>> boo = wrappers.BoolValue(value=True)
>> boo.value
True

>> boo = wrappers.BoolValue(value=False)
>> boo.value
False
like image 200
Oluwafemi Sule Avatar answered Nov 09 '22 12:11

Oluwafemi Sule