False Boolean is not showing in proto3 Python

Question:

I’m using protoBuffer 3 in python it is not showing bool fields correctly.

entity_proto

message Foo {
    string id = 1;
    bool active = 3;
}

Setting values in python.

foo = entity_proto.Foo(id='id-123', active=True)
print(foo)
# id: id-123
# active: True

# But if you set the value False it does not show 'active' in print statement
foo = entity_proto.Foo(id='id-123', active=False)
print(foo)
# id: id-123

if you try to print print(foo.active) output is False which is somehow OK. Main problem is come when I use Http trancoding if I try to print console.log(foo.active) is give me undefined not false (lang: JavaScript)

Can someone please let me know why it is not showing for False values.

Asked By: Azeem Haider

||

Answers:

Protobuf has default values for fields, such as boolean false, numeric zero, or the empty string.

It doesn’t bother encoding those since it’s a waste of space and/or bandwidth (when transmitting). That’s probably why it’s not showing up.

A good way to check this would be to set id to an empty string and see if it behaves similarly:

foo = entity_proto.Foo(id='', active=True)
print(foo)
# active: True (I suspect).

The solution depends really on where that undefined is coming from. Either Javascript has a real undefined value, in which case you can use the null/undefined coalescing operator:

console.log(foo.active ?? false)

Or, if this HTTP transcoder is doing something like creating an literal "undefined" string, you’ll have to figure out how to turn (what is probably) None into "false".

Answered By: paxdiablo

According to the protobuf language guidelines

https://developers.google.com/protocol-buffers/docs/proto3#scalar

“Also note that if a scalar message field is set to its default, the value will not be serialized on the wire.”

So for your boolean field its not even serialized if its default value. The other option for you is to set some int/string field and set it to some value so that you can decide your logic.

Answered By: PraveenB
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.