【问题标题】:Checking for valid enum types from protobufs从 protobufs 检查有效的枚举类型
【发布时间】:2015-12-22 22:28:10
【问题描述】:

在我的名为 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 是否是有效的枚举类型?
即:我该怎么做那条注释行

注意:我想避免对枚举类型的检查进行硬编码,因为我以后可能会添加更多的 VegeType,例如:POTATO = 3, ONION = 4

【问题讨论】:

    标签: python enums protocol-buffers pytest


    【解决方案1】:

    如果我正确理解您的问题,当您使用原型时,如果在分配时给出了不正确的类型,它将在那里引发错误。

    将相关代码包装在 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
        ...
    

    【讨论】:

    • 当时我忘了谢谢你,但整整5年后你给我答案的好意并没有被忘记!!非常感谢你帮助我。
    • 很高兴我能帮上忙! :)
    猜你喜欢
    • 2013-03-20
    • 1970-01-01
    • 2019-12-30
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 2018-10-18
    相关资源
    最近更新 更多