从 protobufs 检查有效的枚举类型
Checking for valid enum types from protobufs
在我名为 skill.proto 的 protobuf 文件中,我有:
message Cooking {
enum VegeType {
CAULIFLOWER = 0;
CUCUMBER = 1;
TOMATO = 2
}
required VegeType type = 1;
}
在另一个文件中(例如:name.py)我想检查文件中的枚举类型是否有效
#if (myCookingStyle.type != skill_pb2.Cooking.VegeTypes):
print "Error: invalid cooking type"
如何检查 myCookingStyle.type 是有效的枚举类型?
即:我该怎么做注释行
注意:我想避免对枚举类型的检查进行硬编码,因为稍后我可能会添加更多 VegeTypes 例如:POTATO = 3, ONION = 4
如果我正确理解你的问题,当你使用原型时,如果在分配时给出了不正确的类型,它将在那里抛出错误。
将相关代码包装在 try...except
块中应该可以解决问题:
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
...
在我名为 skill.proto 的 protobuf 文件中,我有:
message Cooking {
enum VegeType {
CAULIFLOWER = 0;
CUCUMBER = 1;
TOMATO = 2
}
required VegeType type = 1;
}
在另一个文件中(例如:name.py)我想检查文件中的枚举类型是否有效
#if (myCookingStyle.type != skill_pb2.Cooking.VegeTypes):
print "Error: invalid cooking type"
如何检查 myCookingStyle.type 是有效的枚举类型?
即:我该怎么做注释行
注意:我想避免对枚举类型的检查进行硬编码,因为稍后我可能会添加更多 VegeTypes 例如:POTATO = 3, ONION = 4
如果我正确理解你的问题,当你使用原型时,如果在分配时给出了不正确的类型,它将在那里抛出错误。
将相关代码包装在 try...except
块中应该可以解决问题:
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
...