danielgtaylor / python-betterproto

Clean, modern, Python 3.6+ code generator & library for Protobuf 3 and async gRPC
MIT License
1.47k stars 205 forks source link

Cast python dictionary into the betterpoto struct #505

Open ViktorLomakinX opened 1 year ago

ViktorLomakinX commented 1 year ago

Here the template as example:

message Test {
    google.protobuf.Struct data = 1;
}

So, the idea is to add a function to cast a python dictionary in the protobuf structure. The value of dictionary can be any type: int, str, list, dict but we need to automatically set up the fields attribute for the betterproto.lib.google.protobuf.Struct instance. Is this functionality exists? (for now, I just wrote a custom function for it)

Gobot1234 commented 1 year ago

Can you not just call to_dict on data?

ViktorLomakinX commented 1 year ago

Yes, if you have betterproto.lib.google.protobuf.Struct instance and want to cast it to a dictionary, you can invoke to_dict(). What I want, is to cast it from a dictionary to the instance. Of course, we have the from_dict() function which can construct an instance of the betterproto.lib.google.protobuf.Struct class, but you need to prepare the dictionary, cause it requires specifying the type for each dictionary key and value. Anyway, I need a helper function to prepare my dictionary. I am looking for this function in the lib sources, but for now, do not found it. Interestingly, the protobuf package from Google has such a function, so you just pass a dictionary into and get the result struct. Any ideas?