Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically access oneof value from a protobuf

Let's say I defined a protobuf message like this

message Config {
    oneof config{
         A a = 1;
         B b = 2;
    }
}

now inside python code, when I am parsing a message instance of Config, I can get the one of field name with

field = config.WhichOneof('config')

but how should I access A with the fieldname I got? I don't want to write something like:

if field == 'a':
    return config.a
else
    return config.b

because I just want to get the underline value with either a or b, I already know its type. Is there a better solution? thanks!

like image 681
ustcyue Avatar asked Jul 19 '18 11:07

ustcyue


People also ask

What is oneof in Protobuf?

Protocol Buffer (Protobuf) provides two simpler options for dealing with values that might be of more than one type. The Any type can represent any known Protobuf message type. And you can use the oneof keyword to specify that only one of a range of fields can be set in any message.

Does Protobuf support inheritance?

Inheritance is not supported in protocol buffers.

Can you remove fields from Protobuf?

Removing fields is fine, although you might want to mark it reserved so that nobody reuses it in an incompatible way. New code with old data (with the field) will silently ignore it; old code with new data will just load without the field populated, since everything in proto3 is implicitly optional .


1 Answers

You can use getattr:

data = getattr(config, config.WhichOneof('config')).value

Since WhichOneof('config') returns either 'a' or 'b', just use getattr to access the attribute dynamically.

like image 58
cs95 Avatar answered Sep 28 '22 17:09

cs95