Skip to content
This repository was archived by the owner on Feb 23, 2026. It is now read-only.

Commit 41c8499

Browse files
committed
improved PROTOBUF_VERSION in prep for 10+
1 parent 89e5ac2 commit 41c8499

1 file changed

Lines changed: 11 additions & 7 deletions

File tree

proto/message.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@
3636

3737
PROTOBUF_VERSION = google.protobuf.__version__
3838

39+
# extract the major version code
40+
_separator_idx = PROTOBUF_VERSION.find('.')
41+
_PROTOBUF_MAJOR_VERSION = PROTOBUF_VERSION[:_separator_idx] if _separator_idx != -1 else PROTOBUF_VERSION
42+
3943
_upb = has_upb() # Important to cache result here.
4044

4145

@@ -383,7 +387,7 @@ def _warn_if_including_default_value_fields_is_used_protobuf_5(
383387
including_default_value_fields (Optional(bool)): The value of `including_default_value_fields` set by the user.
384388
"""
385389
if (
386-
PROTOBUF_VERSION[0] not in ("3", "4")
390+
_PROTOBUF_MAJOR_VERSION not in ("3", "4")
387391
and including_default_value_fields is not None
388392
):
389393
warnings.warn(
@@ -918,30 +922,30 @@ def _message_to_map(
918922
instance,
919923
*,
920924
including_default_value_fields=None,
921-
float_precision=None,
922925
always_print_fields_with_no_presence=None,
926+
float_precision=None,
923927
**kwargs,
924928
):
925929
"""
926930
Helper for logic for Message.to_dict and Message.to_json
927931
"""
928-
print_fields = cls._normalize_print_fields_without_presence(
929-
always_print_fields_with_no_presence, including_default_value_fields
930-
)
931932

932933
# The `including_default_value_fields` argument was removed from protobuf 5.x
933934
# and replaced with `always_print_fields_with_no_presence` which very similar but has
934935
# handles optional fields consistently by not affecting them.
935936
# The old flag accidentally had inconsistent behavior between proto2
936937
# optional and proto3 optional fields.
937-
if PROTOBUF_VERSION[0] in ("3", "4"):
938+
print_fields = cls._normalize_print_fields_without_presence(
939+
always_print_fields_with_no_presence, including_default_value_fields
940+
)
941+
if _PROTOBUF_MAJOR_VERSION in ("3", "4"):
938942
kwargs["including_default_value_fields"] = print_fields
939943
else:
940944
kwargs["always_print_fields_with_no_presence"] = print_fields
941945

942946
if float_precision:
943947
# float_precision removed in protobuf 7
944-
if int(PROTOBUF_VERSION[0]) < 7:
948+
if _PROTOBUF_MAJOR_VERSION in ("3", "4", "5", "6"):
945949
kwargs["float_precision"] = float_precision
946950
else:
947951
warnings.warn(

0 commit comments

Comments
 (0)