从protobuf检查有效的枚举类型 [英] Checking for valid enum types from protobufs

查看:1021
本文介绍了从protobuf检查有效的枚举类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 消息烹饪{
枚举VegeType {
CAULIFLOWER = 0;
CUCUMBER = 1;
TOMATO = 2
}

必需VegeType type = 1;
}

在另一个文件(例如:name.py)中,我想检查文件中的枚举是一个有效的类型

  #if(myCookingStyle.type!= skill_pb2.Cooking.VegeTypes):
打印错误:无效的烹饪类型

如何检查myCookingStyle.type是否是有效的枚举类型?

ie:如何做这个评论行



注意:我想避免对枚举类型,因为我可能以后添加更多的VegeTypes例如:POTATO = 3,ONION = 4

解决方案

正确地理解你的问题,当你使用proto时,如果给定一个不正确的类型,它会在那里发生错误。



将相关代码包含在code> try ...除了块应该做的诀窍:

  try:
proto = skill_pb2.Cooking()
proto.type = 6#不正确的类型是屁股点击
除了ValueError作为e:#以上分配引发一个ValueError,在这里捕获
打印'分配给烹饪原型的不正确的类型'
raise
else:
#使用proto .type这里自由 - 如果它被分配成功,它包含一个有效的类型
print proto.type
...


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

解决方案

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

这篇关于从protobuf检查有效的枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆