gpt4 book ai didi

python - 从 protobufs 检查有效的枚举类型

转载 作者:行者123 更新时间:2023-12-04 16:44:58 25 4
gpt4 key购买 nike

在我名为 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

最佳答案

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

将相关代码包装在 try...except block 中应该可以解决问题:

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

关于python - 从 protobufs 检查有效的枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34425502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com