python-betterproto icon indicating copy to clipboard operation
python-betterproto copied to clipboard

Cast python dictionary into the betterpoto struct

Open ViktorLomakinX opened this issue 2 years ago • 3 comments

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)

ViktorLomakinX avatar Jun 21 '23 08:06 ViktorLomakinX

Can you not just call to_dict on data?

Gobot1234 avatar Jun 27 '23 17:06 Gobot1234

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?

ViktorLomakinX avatar Jun 28 '23 07:06 ViktorLomakinX