Reputation: 651
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!
Upvotes: 36
Views: 30215
Reputation: 402593
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.
Upvotes: 51