I'm currently using protobuff3 on Python 3.7 to serialize packets and transfer them over the network. Before refactoring, I was using a regular enum, but now I've moved on to protobuff enums. However I did not find a way to check if the value is in the enum. In plain python I would do it if item in enum:. What would be the best way to do it ?
My protobuff file:
syntax = "proto3";
package vlcTogether;
message defaultPacket {
    Commands command = 1;
    string param = 2;
    enum Commands {
        ERROR = 0;
        JOIN = 1;
        QUIT = 2;
        VLC_COMMAND = 3;
        SERVER_INFO = 4;
    }
}
The defaultPacket of google.protobuf.pyext.cpp_message.GeneratedProtocolMessageType has a Commands attribute.
This attribute is an instance of google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper and has the following methods Name and Value.
The Name method returns the name for an integer when it exists in the Enum or raises a ValueError.
The Value method returns the value for a string when it exists in the Enum or raises a ValueError similarly.
def valuenum_in_enum(enum_wrapper, valuenum):
    try:
        if enum_wrapper.Name(valuenum):
            return True
    except ValueError:
        return False
def valuename_in_enum(enum_wrapper, valuename):
    try:
        if enum_wrapper.Value(valuename):
            return True
    except ValueError:
        return False 
>>> valuenum_in_enum(defaultPacket.Commands, 2)
True
>>> valuename_in_enum(defaultPacket.Commands, 'QUIT')
True
Another straight-forward approach is using DESCRIPTOR attribute of Commands. 
It has values_by_number and values_by_name properties that return mappings.
For example,
>>> commands_descriptor = defaultPacket.Commands.DESCRIPTOR
>>> 'QUIT' in commands_descriptor.values_by_name
>>> 2 in commands_descriptor.values_by_number
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With