Checking for valid enum types from protobufs

六眼飞鱼酱① 提交于 2019-12-23 03:51:51

问题


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
    ...


来源:https://stackoverflow.com/questions/34425502/checking-for-valid-enum-types-from-protobufs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!