Skip to content

Commit 385d5d4

Browse files
fix(proto): convert map keys from string to int during deserialization (#100)
* fix(proto): convert map keys from string to int during deserialization Fixed an issue where map keys remained as strings instead of being converted to integers during deserialization. Added proper type conversion using _value_from_dict for map keys to ensure correct integer type conversion. * Update src/betterproto2/__init__.py Co-authored-by: Adrien <[email protected]> --------- Co-authored-by: Adrien <[email protected]>
1 parent 50d0edc commit 385d5d4

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

src/betterproto2/__init__.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,12 @@
6666
# Fields that are numerical 64-bit types
6767
INT_64_TYPES = [TYPE_INT64, TYPE_UINT64, TYPE_SINT64, TYPE_FIXED64, TYPE_SFIXED64]
6868

69+
# Fields that are numerical 32-bit types
70+
INT_32_TYPES = [TYPE_INT32, TYPE_UINT32, TYPE_SINT32, TYPE_FIXED32, TYPE_SFIXED32]
71+
72+
# Fields that are numerical types
73+
ALL_INT_TYPES = INT_64_TYPES + INT_32_TYPES
74+
6975
# Fields that are efficiently packed when
7076
PACKED_TYPES = [
7177
TYPE_ENUM,
@@ -598,7 +604,7 @@ def _value_from_dict(value: Any, meta: FieldMetadata, field_type: type) -> Any:
598604
return value
599605
raise ValueError("Enum value must be a string or an Enum instance")
600606

601-
if meta.proto_type in INT_64_TYPES: # TODO all integer types
607+
if meta.proto_type in ALL_INT_TYPES:
602608
return int(value)
603609

604610
if meta.proto_type == TYPE_BYTES:
@@ -1087,7 +1093,10 @@ def _from_dict_init(cls, mapping: Mapping[str, Any] | Any) -> Mapping[str, Any]:
10871093

10881094
value_cls = cls._betterproto.cls_by_field[f"{field_name}.value"]
10891095

1090-
value = {k: _value_from_dict(v, meta.map_meta[1], value_cls) for k, v in value.items()}
1096+
value = {
1097+
_value_from_dict(k, meta.map_meta[0], type(None)): _value_from_dict(v, meta.map_meta[1], value_cls)
1098+
for k, v in value.items()
1099+
}
10911100

10921101
elif meta.repeated:
10931102
value = [_value_from_dict(item, meta, field_cls) for item in value]

0 commit comments

Comments
 (0)