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!
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.
Inheritance is not supported in protocol buffers.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With