2015-12-22 33 views
1

在我的protobuf文件名爲skill.proto有效枚舉類型,我有:檢查從protobufs

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是否爲有效的枚舉類型?
即:我怎麼做到這一點的註釋行

NB:我想避免這樣做很難檢查的枚舉類型的編碼,因爲我可能以後添加更多VegeTypes如:土豆= 3,蔥= 4

回答

0

如果我正確理解你的問題,當你使用proto時,如果在賦值時給出了一個不正確的類型,它會在那裏拋出一個錯誤。

結束語在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 
    ...