Checking for valid enum types from protobufs

2019-06-08 09:18发布

问题:

In my protobuf file called skill.proto, I have:

message Cooking {
     enum VegeType {
         CAULIFLOWER = 0;
         CUCUMBER = 1;
         TOMATO = 2
     }

required VegeType type = 1;
}

In another file (eg: name.py) I want to check that the enum within the file is a valid type

#if (myCookingStyle.type != skill_pb2.Cooking.VegeTypes):
   print "Error: invalid cooking type"

How do I check that myCookingStyle.type is a valid enum type?
ie: how do I do that commented line

NB: I want to avoid doing hard coding of the checking for the enum types because I might later on add more VegeTypes eg: POTATO = 3, ONION = 4

回答1:

If I understand your question correctly, when you are using the proto, if an incorrect type is given on assignment it will throw an error there.

Wrapping the relevant code in a try...except block should do the trick:

try:
    proto = skill_pb2.Cooking()
    proto.type = 6 # Incorrect type being assigned
except ValueError as e: # Above assignment throws a ValueError, caught here
    print 'Incorrect type assigned to Cooking proto'
    raise
else:
    # Use proto.type here freely - if it has been assigned to successfully, it contains a valid type
    print proto.type
    ...