Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over a protobuff enum in python

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;
    }
}
like image 623
Clément Péau Avatar asked Sep 17 '25 23:09

Clément Péau


1 Answers

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
like image 86
Oluwafemi Sule Avatar answered Sep 19 '25 14:09

Oluwafemi Sule