I have a protobuf definition like below,
message MyProto {
optional string ip = 1;
optional int32 port = 2;
optional Flags flags = 3;
}
message Flags {
optional bool flag1 = 1;
optional bool flag2 = 2;
}
My goal is to create a MyProto object from the below string:
ip:127.0.0.1
port:8080
Flags:
flag1: True
flag2: False
I can generate an “empty” object with my_proto = MyProto(), and can set the attribute of it by using
setattr(my_proto, "ip", "127.0.0.1")
setattr(my_proto, "port", 8080)
but cannot figure out how to “fill in” the Flags
message into my_proto. Is there any general way to do that? By general way, I mean assume we need to figure out the message name of Flags
from the string
Flags:
flag1: True
flag2: False
(because there could be other message definitions used in MyProto
)
4
foo.proto
:
syntax = "proto3";
message MyProto {
optional string ip = 1;
optional int32 port = 2;
optional Flags flags = 3;
}
message Flags {
optional bool flag1 = 1;
optional bool flag2 = 2;
}
protoc
--python_out=${PWD}
--pyi_out=${PWD}
foo.proto
requirements.txt
:
protobuf==5.28.2
main.py
:
from foo_pb2 import MyProto,Flags
my_proto = MyProto(
ip="192.168.1.1",
port=8080,
flags=Flags(
flag1=True,
flag2=False
)
)
print(my_proto)
ip: "192.168.1.1"
port: 8080
flags {
flag1: true
flag2: false
}
You can use setattr
but it’s preferable to use the constructor of the class generated for each Messsage
or reference fields directly (e.g. my_proto.ip = "foo"
) .
Because MyProto
and Flags
are both messages, both must be constructed before use.
2