ustcyue
ustcyue

Reputation: 651

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!

Upvotes: 36

Views: 30215

Answers (1)

cs95
cs95

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

Related Questions