Skip to content

Commit 85e4be9

Browse files
GrownNedabn
andauthored
fix Message.to_dict mutating the underlying Message (#378)
* [fix] to_dict modifies the underlying message (#151) * add test for mapmessage * fix for to_dict * formatting * Apply suggestions from code review Co-authored-by: Arun Babu Neelicattu <[email protected]> * change to_json to to_dict Co-authored-by: Arun Babu Neelicattu <[email protected]>
1 parent 06c26ba commit 85e4be9

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

src/betterproto/__init__.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1123,12 +1123,13 @@ def to_dict(
11231123
):
11241124
output[cased_name] = value.to_dict(casing, include_default_values)
11251125
elif meta.proto_type == TYPE_MAP:
1126+
output_map = {**value}
11261127
for k in value:
11271128
if hasattr(value[k], "to_dict"):
1128-
value[k] = value[k].to_dict(casing, include_default_values)
1129+
output_map[k] = value[k].to_dict(casing, include_default_values)
11291130

11301131
if value or include_default_values:
1131-
output[cased_name] = value
1132+
output[cased_name] = output_map
11321133
elif (
11331134
value != self._get_field_default(field_name)
11341135
or include_default_values

tests/test_mapmessage.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from tests.output_betterproto.mapmessage import (
2+
Nested,
3+
Test,
4+
)
5+
6+
7+
def test_mapmessage_to_dict_preserves_message():
8+
message = Test(
9+
items={
10+
"test": Nested(
11+
count=1,
12+
)
13+
}
14+
)
15+
16+
message.to_dict()
17+
18+
assert isinstance(message.items["test"], Nested), "Wrong nested type after to_dict"

0 commit comments

Comments
 (0)