Skip to content

betterproto: support Struct and Value #551

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jan 2, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions src/betterproto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@
hybridmethod,
)


if TYPE_CHECKING:
from _typeshed import (
SupportsRead,
Expand Down Expand Up @@ -1404,6 +1403,15 @@ def to_dict(
Dict[:class:`str`, Any]
The JSON serializable dict representation of this object.
"""
# Mirror of from_dict: Struct's `fields` member is transparently
# dispatched through instead.
if isinstance(self, Struct):
output = {**self.fields}
for k in self.fields:
if hasattr(self.fields[k], "to_dict"):
output[k] = self.fields[k].to_dict(casing, include_default_values)
return output

output: Dict[str, Any] = {}
field_types = self._type_hints()
defaults = self._betterproto.default_gen
Expand Down Expand Up @@ -1522,6 +1530,12 @@ def to_dict(

@classmethod
def _from_dict_init(cls, mapping: Mapping[str, Any]) -> Mapping[str, Any]:
# Special case: google.protobuf.Struct has a single fields member but
# behaves like a transparent JSON object, so it needs to first be munged
# into `{fields: mapping}`.
if cls == Struct:
mapping = {"fields": mapping}

init_kwargs: Dict[str, Any] = {}
for key, value in mapping.items():
field_name = safe_snake_case(key)
Expand Down Expand Up @@ -1552,7 +1566,7 @@ def _from_dict_init(cls, mapping: Mapping[str, Any]) -> Mapping[str, Any]:
if isinstance(value, list)
else sub_cls.from_dict(value)
)
elif meta.map_types and meta.map_types[1] == TYPE_MESSAGE:
elif meta.map_types and meta.map_types[1] == TYPE_MESSAGE and cls != Struct:
sub_cls = cls._betterproto.cls_by_field[f"{field_name}.value"]
value = {k: sub_cls.from_dict(v) for k, v in value.items()}
else:
Expand Down Expand Up @@ -1582,6 +1596,7 @@ def _from_dict_init(cls, mapping: Mapping[str, Any]) -> Mapping[str, Any]:
)

init_kwargs[field_name] = value

return init_kwargs

@hybridmethod
Expand Down Expand Up @@ -1926,6 +1941,7 @@ def which_one_of(message: Message, group_name: str) -> Tuple[str, Optional[Any]]
Int32Value,
Int64Value,
StringValue,
Struct,
Timestamp,
UInt32Value,
UInt64Value,
Expand Down
22 changes: 22 additions & 0 deletions tests/test_struct.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import json

from betterproto.lib.google.protobuf import Struct


def test_struct_roundtrip():
data = {
"foo": "bar",
"baz": None,
"quux": 123,
"zap": [1, {"two": 3}, "four"],
}
data_json = json.dumps(data)

struct_from_dict = Struct().from_dict(data)
assert struct_from_dict.fields == data
assert struct_from_dict.to_json() == data_json

struct_from_json = Struct().from_json(data_json)
assert struct_from_json.fields == data
assert struct_from_json == struct_from_dict
assert struct_from_json.to_json() == data_json