api_implementation.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # https://developers.google.com/protocol-buffers/
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Determine which implementation of the protobuf API is used in this process.
  31. """
  32. import os
  33. import warnings
  34. import sys
  35. try:
  36. # pylint: disable=g-import-not-at-top
  37. from google.protobuf.internal import _api_implementation
  38. # The compile-time constants in the _api_implementation module can be used to
  39. # switch to a certain implementation of the Python API at build time.
  40. _api_version = _api_implementation.api_version
  41. _proto_extension_modules_exist_in_build = True
  42. except ImportError:
  43. _api_version = -1 # Unspecified by compiler flags.
  44. _proto_extension_modules_exist_in_build = False
  45. if _api_version == 1:
  46. raise ValueError('api_version=1 is no longer supported.')
  47. if _api_version < 0: # Still unspecified?
  48. try:
  49. # The presence of this module in a build allows the proto implementation to
  50. # be upgraded merely via build deps rather than a compiler flag or the
  51. # runtime environment variable.
  52. # pylint: disable=g-import-not-at-top
  53. from google.protobuf import _use_fast_cpp_protos
  54. # Work around a known issue in the classic bootstrap .par import hook.
  55. if not _use_fast_cpp_protos:
  56. raise ImportError('_use_fast_cpp_protos import succeeded but was None')
  57. del _use_fast_cpp_protos
  58. _api_version = 2
  59. except ImportError:
  60. try:
  61. # pylint: disable=g-import-not-at-top
  62. from google.protobuf.internal import use_pure_python
  63. del use_pure_python # Avoids a pylint error and namespace pollution.
  64. except ImportError:
  65. # TODO(b/74017912): It's unsafe to enable :use_fast_cpp_protos by default;
  66. # it can cause data loss if you have any Python-only extensions to any
  67. # message passed back and forth with C++ code.
  68. #
  69. # TODO(b/17427486): Once that bug is fixed, we want to make both Python 2
  70. # and Python 3 default to `_api_version = 2` (C++ implementation V2).
  71. pass
  72. _default_implementation_type = (
  73. 'python' if _api_version <= 0 else 'cpp')
  74. # This environment variable can be used to switch to a certain implementation
  75. # of the Python API, overriding the compile-time constants in the
  76. # _api_implementation module. Right now only 'python' and 'cpp' are valid
  77. # values. Any other value will be ignored.
  78. _implementation_type = os.getenv('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION',
  79. _default_implementation_type)
  80. if _implementation_type != 'python':
  81. _implementation_type = 'cpp'
  82. if 'PyPy' in sys.version and _implementation_type == 'cpp':
  83. warnings.warn('PyPy does not work yet with cpp protocol buffers. '
  84. 'Falling back to the python implementation.')
  85. _implementation_type = 'python'
  86. # This environment variable can be used to switch between the two
  87. # 'cpp' implementations, overriding the compile-time constants in the
  88. # _api_implementation module. Right now only '2' is supported. Any other
  89. # value will cause an error to be raised.
  90. _implementation_version_str = os.getenv(
  91. 'PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION_VERSION', '2')
  92. if _implementation_version_str != '2':
  93. raise ValueError(
  94. 'unsupported PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION_VERSION: "' +
  95. _implementation_version_str + '" (supported versions: 2)'
  96. )
  97. _implementation_version = int(_implementation_version_str)
  98. # Detect if serialization should be deterministic by default
  99. try:
  100. # The presence of this module in a build allows the proto implementation to
  101. # be upgraded merely via build deps.
  102. #
  103. # NOTE: Merely importing this automatically enables deterministic proto
  104. # serialization for C++ code, but we still need to export it as a boolean so
  105. # that we can do the same for `_implementation_type == 'python'`.
  106. #
  107. # NOTE2: It is possible for C++ code to enable deterministic serialization by
  108. # default _without_ affecting Python code, if the C++ implementation is not in
  109. # use by this module. That is intended behavior, so we don't actually expose
  110. # this boolean outside of this module.
  111. #
  112. # pylint: disable=g-import-not-at-top,unused-import
  113. from google.protobuf import enable_deterministic_proto_serialization
  114. _python_deterministic_proto_serialization = True
  115. except ImportError:
  116. _python_deterministic_proto_serialization = False
  117. # Usage of this function is discouraged. Clients shouldn't care which
  118. # implementation of the API is in use. Note that there is no guarantee
  119. # that differences between APIs will be maintained.
  120. # Please don't use this function if possible.
  121. def Type():
  122. return _implementation_type
  123. # See comment on 'Type' above.
  124. def Version():
  125. return _implementation_version
  126. # For internal use only
  127. def IsPythonDefaultSerializationDeterministic():
  128. return _python_deterministic_proto_serialization
  129. # DO NOT USE: For migration and testing only. Will be removed when Proto3
  130. # defaults to preserve unknowns.
  131. if _implementation_type == 'cpp':
  132. try:
  133. # pylint: disable=g-import-not-at-top
  134. from google.protobuf.pyext import _message
  135. def GetPythonProto3PreserveUnknownsDefault():
  136. return _message.GetPythonProto3PreserveUnknownsDefault()
  137. def SetPythonProto3PreserveUnknownsDefault(preserve):
  138. _message.SetPythonProto3PreserveUnknownsDefault(preserve)
  139. except ImportError:
  140. # Unrecognized cpp implementation. Skipping the unknown fields APIs.
  141. pass
  142. else:
  143. _python_proto3_preserve_unknowns_default = True
  144. def GetPythonProto3PreserveUnknownsDefault():
  145. return _python_proto3_preserve_unknowns_default
  146. def SetPythonProto3PreserveUnknownsDefault(preserve):
  147. global _python_proto3_preserve_unknowns_default
  148. _python_proto3_preserve_unknowns_default = preserve