|
36 | 36 |
|
37 | 37 | PROTOBUF_VERSION = google.protobuf.__version__ |
38 | 38 |
|
| 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 | + |
39 | 43 | _upb = has_upb() # Important to cache result here. |
40 | 44 |
|
41 | 45 |
|
@@ -383,7 +387,7 @@ def _warn_if_including_default_value_fields_is_used_protobuf_5( |
383 | 387 | including_default_value_fields (Optional(bool)): The value of `including_default_value_fields` set by the user. |
384 | 388 | """ |
385 | 389 | if ( |
386 | | - PROTOBUF_VERSION[0] not in ("3", "4") |
| 390 | + _PROTOBUF_MAJOR_VERSION not in ("3", "4") |
387 | 391 | and including_default_value_fields is not None |
388 | 392 | ): |
389 | 393 | warnings.warn( |
@@ -918,30 +922,30 @@ def _message_to_map( |
918 | 922 | instance, |
919 | 923 | *, |
920 | 924 | including_default_value_fields=None, |
921 | | - float_precision=None, |
922 | 925 | always_print_fields_with_no_presence=None, |
| 926 | + float_precision=None, |
923 | 927 | **kwargs, |
924 | 928 | ): |
925 | 929 | """ |
926 | 930 | Helper for logic for Message.to_dict and Message.to_json |
927 | 931 | """ |
928 | | - print_fields = cls._normalize_print_fields_without_presence( |
929 | | - always_print_fields_with_no_presence, including_default_value_fields |
930 | | - ) |
931 | 932 |
|
932 | 933 | # The `including_default_value_fields` argument was removed from protobuf 5.x |
933 | 934 | # and replaced with `always_print_fields_with_no_presence` which very similar but has |
934 | 935 | # handles optional fields consistently by not affecting them. |
935 | 936 | # The old flag accidentally had inconsistent behavior between proto2 |
936 | 937 | # 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"): |
938 | 942 | kwargs["including_default_value_fields"] = print_fields |
939 | 943 | else: |
940 | 944 | kwargs["always_print_fields_with_no_presence"] = print_fields |
941 | 945 |
|
942 | 946 | if float_precision: |
943 | 947 | # float_precision removed in protobuf 7 |
944 | | - if int(PROTOBUF_VERSION[0]) < 7: |
| 948 | + if _PROTOBUF_MAJOR_VERSION in ("3", "4", "5", "6"): |
945 | 949 | kwargs["float_precision"] = float_precision |
946 | 950 | else: |
947 | 951 | warnings.warn( |
|
0 commit comments