@@ -1108,16 +1108,23 @@ def to_dict(
1108
1108
return output
1109
1109
1110
1110
@classmethod
1111
- def _from_dict_init (cls , mapping : Mapping [str , Any ] | Any ) -> Mapping [str , Any ]:
1111
+ def _from_dict_init (cls , mapping : Mapping [str , Any ] | Any , * , ignore_unknown_fields : bool ) -> Mapping [str , Any ]:
1112
1112
init_kwargs : dict [str , Any ] = {}
1113
1113
for key , value in mapping .items ():
1114
1114
field_name = safe_snake_case (key )
1115
- field_cls = cls ._betterproto .cls_by_field [field_name ]
1116
1115
1117
1116
try :
1117
+ field_cls = cls ._betterproto .cls_by_field [field_name ]
1118
1118
meta = cls ._betterproto .meta_by_field_name [field_name ]
1119
1119
except KeyError :
1120
- continue # TODO is it a problem?
1120
+ # According to the protobuf spec (https://protobuf.dev/programming-guides/json/): "The protobuf JSON
1121
+ # parser should reject unknown fields by default but may provide an option to ignore unknown fields in
1122
+ # parsing."
1123
+ if ignore_unknown_fields :
1124
+ continue
1125
+
1126
+ raise KeyError (f"Unknown field '{ field_name } ' in message { cls .__name__ } ." ) from None
1127
+
1121
1128
if value is None :
1122
1129
continue
1123
1130
@@ -1148,7 +1155,7 @@ def _from_dict_init(cls, mapping: Mapping[str, Any] | Any) -> Mapping[str, Any]:
1148
1155
return init_kwargs
1149
1156
1150
1157
@classmethod
1151
- def from_dict (cls : type [Self ], value : Mapping [str , Any ] | Any ) -> Self :
1158
+ def from_dict (cls : type [Self ], value : Mapping [str , Any ] | Any , * , ignore_unknown_fields : bool = False ) -> Self :
1152
1159
"""
1153
1160
Parse the key/value pairs into the a new message instance.
1154
1161
@@ -1165,7 +1172,7 @@ def from_dict(cls: type[Self], value: Mapping[str, Any] | Any) -> Self:
1165
1172
if not isinstance (value , Mapping ) and hasattr (cls , "from_wrapped" ): # type: ignore
1166
1173
return cls .from_wrapped (value ) # type: ignore
1167
1174
1168
- return cls (** cls ._from_dict_init (value ))
1175
+ return cls (** cls ._from_dict_init (value , ignore_unknown_fields = ignore_unknown_fields )) # type: ignore
1169
1176
1170
1177
def to_json (
1171
1178
self ,
0 commit comments