If I want to add a value to a field in a protocol buffer that isn’t known at compile time, I’m currently doing setattr
. I normally don’t like using setattr
because it seems less secure. But when I know the object is a protobuf, I’m thinking it is fine, because the value I’m setting it to must be of the type that the protobuf allows. So maybe it isn’t really unsafe??
Let me explain by example. First, assume I have this protobuf:
message Person {
string first_name = 1;
string second_name = 1;
int age = 3;
}
Then I have some code that uses the above protobuf:
from person_pb2 import Person
my_info = {"first_name": "Mike", "last_name": "example", "age": 999}
me = Person()
for field, value in my_info:
setattr(me, field, value)
This is a very flexible way to handle the protobuf. I cannot, for instance, specify it like I would in a dict
, saying me[field] = value
. Yet, me[field] = value
is perfectly safe. If the value is of the wrong type for the field/attribute when using setattr
, I’ll get an error: TypeError: bad argument type for built-in operation
So, I’m tempted to say that for protobufs, using setattr
is completely fine and, in fact, is really the only way to programmatically add values to the protobuf fields. Is this correct? Is there a better or safer way? I cannot do something like me.first_name = "Mike"
because I need it to be programmatic.