Skip to content

[fix] to_dict modifies the underlying message (#151) #378

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 6 commits into from
May 9, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 3 additions & 2 deletions src/betterproto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1124,12 +1124,13 @@ def to_dict(
):
output[cased_name] = value.to_dict(casing, include_default_values)
elif meta.proto_type == TYPE_MAP:
output_map = {**value}
for k in value:
if hasattr(value[k], "to_dict"):
value[k] = value[k].to_dict(casing, include_default_values)
output_map[k] = value[k].to_dict(casing, include_default_values)

if value or include_default_values:
output[cased_name] = value
output[cased_name] = output_map
elif (
value != self._get_field_default(field_name)
or include_default_values
Expand Down
18 changes: 18 additions & 0 deletions tests/test_mapmessage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from tests.output_betterproto.mapmessage import (
Nested,
Test,
)


def test_mapmessage_to_dict_preserves_message():
message = Test(
items={
"test": Nested(
count=1,
)
}
)

message.to_dict()

assert isinstance(message.items["test"], Nested), "Wrong nested type after to_dict"