Given a compiled Python protobuf as follows:

message Person {
    optional string email = 1;
}

Don’t use duck typing to see if an optional field has been set!

Though the value is known to be unset, accessing the value always returns a default value! (Source. See optional field description.)

import Person_pb2

person = Person()

if person.email:
    print('Oh wow you totally have an email!')
    print('It is: '.format(person.email))
else:
    print('I got nothing')

> Oh wow you totally have an email!

> It is:

Use the compiled protobuf’s data member functions to check existance:

if person.HasField('email'):
    # do stuff

It’s not very clear you need to do it like this…