matlab-prodserver-client 24.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. google/__init__.py +7 -0
  2. google/protobuf_ml/__init__.py +33 -0
  3. google/protobuf_ml/descriptor.py +1230 -0
  4. google/protobuf_ml/descriptor_database.py +177 -0
  5. google/protobuf_ml/descriptor_pb2.py +1925 -0
  6. google/protobuf_ml/descriptor_pool.py +1295 -0
  7. google/protobuf_ml/internal/__init__.py +0 -0
  8. google/protobuf_ml/internal/_parameterized.py +443 -0
  9. google/protobuf_ml/internal/api_implementation.py +168 -0
  10. google/protobuf_ml/internal/builder.py +130 -0
  11. google/protobuf_ml/internal/containers.py +708 -0
  12. google/protobuf_ml/internal/decoder.py +1068 -0
  13. google/protobuf_ml/internal/descriptor_database_test.py +127 -0
  14. google/protobuf_ml/internal/descriptor_pool_test.py +1149 -0
  15. google/protobuf_ml/internal/descriptor_test.py +1076 -0
  16. google/protobuf_ml/internal/encoder.py +829 -0
  17. google/protobuf_ml/internal/enum_type_wrapper.py +124 -0
  18. google/protobuf_ml/internal/extension_dict.py +213 -0
  19. google/protobuf_ml/internal/generator_test.py +354 -0
  20. google/protobuf_ml/internal/import_test.py +49 -0
  21. google/protobuf_ml/internal/json_format_test.py +1285 -0
  22. google/protobuf_ml/internal/keywords_test.py +103 -0
  23. google/protobuf_ml/internal/message_factory_test.py +299 -0
  24. google/protobuf_ml/internal/message_listener.py +78 -0
  25. google/protobuf_ml/internal/message_test.py +2573 -0
  26. google/protobuf_ml/internal/proto_builder_test.py +106 -0
  27. google/protobuf_ml/internal/python_message.py +1539 -0
  28. google/protobuf_ml/internal/reflection_test.py +3381 -0
  29. google/protobuf_ml/internal/service_reflection_test.py +139 -0
  30. google/protobuf_ml/internal/symbol_database_test.py +133 -0
  31. google/protobuf_ml/internal/test_util.py +878 -0
  32. google/protobuf_ml/internal/testing_refleaks.py +142 -0
  33. google/protobuf_ml/internal/text_encoding_test.py +67 -0
  34. google/protobuf_ml/internal/text_format_test.py +2447 -0
  35. google/protobuf_ml/internal/type_checkers.py +435 -0
  36. google/protobuf_ml/internal/unknown_fields_test.py +461 -0
  37. google/protobuf_ml/internal/well_known_types.py +887 -0
  38. google/protobuf_ml/internal/well_known_types_test.py +1013 -0
  39. google/protobuf_ml/internal/wire_format.py +268 -0
  40. google/protobuf_ml/internal/wire_format_test.py +252 -0
  41. google/protobuf_ml/json_format.py +912 -0
  42. google/protobuf_ml/message.py +424 -0
  43. google/protobuf_ml/message_factory.py +189 -0
  44. google/protobuf_ml/proto_builder.py +134 -0
  45. google/protobuf_ml/reflection.py +95 -0
  46. google/protobuf_ml/service.py +228 -0
  47. google/protobuf_ml/service_reflection.py +295 -0
  48. google/protobuf_ml/symbol_database.py +194 -0
  49. google/protobuf_ml/text_encoding.py +110 -0
  50. google/protobuf_ml/text_format.py +1842 -0
  51. google/protobuf_ml/unknown_fields.py +120 -0
  52. matlab/__init__.py +43 -0
  53. matlab/bin/win64/libmwfoundation_matlabdata.dll +0 -0
  54. matlab/bin/win64/libmwfoundation_matlabdata_standalone.dll +0 -0
  55. matlab/extern/bin/win64/libMatlabDataArray.dll +0 -0
  56. matlab/extern/bin/win64/matlabmultidimarrayforpython.cp310-win_amd64.pyd +0 -0
  57. matlab/extern/bin/win64/matlabmultidimarrayforpython.cp39-win_amd64.pyd +0 -0
  58. matlab/extern/bin/win64/matlabmultidimarrayforpython.pyd +0 -0
  59. matlab/production_server/__init__.py +2 -0
  60. matlab/production_server/_internal_mps/__init__.py +2 -0
  61. matlab/production_server/_internal_mps/feval_handler.py +76 -0
  62. matlab/production_server/_internal_mps/invocation_handler_utils.py +52 -0
  63. matlab/production_server/_internal_mps/matlab_array_builder.py +201 -0
  64. matlab/production_server/_internal_mps/matlab_response_builder.py +134 -0
  65. matlab/production_server/_proto_generated/MATLABArray_pb2.py +129 -0
  66. matlab/production_server/_proto_generated/MATLABError_pb2.py +27 -0
  67. matlab/production_server/_proto_generated/MATLABParams_pb2.py +26 -0
  68. matlab/production_server/_proto_generated/MATLABResult_pb2.py +27 -0
  69. matlab/production_server/_proto_generated/__init__.py +0 -0
  70. matlab/production_server/client.py +140 -0
  71. matlab/production_server/mpsexceptions.py +56 -0
  72. matlab_prodserver_client-24.2.dist-info/LICENSE.txt +27 -0
  73. matlab_prodserver_client-24.2.dist-info/METADATA +94 -0
  74. matlab_prodserver_client-24.2.dist-info/RECORD +77 -0
  75. matlab_prodserver_client-24.2.dist-info/WHEEL +5 -0
  76. matlab_prodserver_client-24.2.dist-info/top_level.txt +3 -0
  77. six.py +953 -0
File without changes
@@ -0,0 +1,443 @@
1
+ #! /usr/bin/env python
2
+ #
3
+ # Protocol Buffers - Google's data interchange format
4
+ # Copyright 2008 Google Inc. All rights reserved.
5
+ # https://developers.google.com/protocol-buffers/
6
+ #
7
+ # Redistribution and use in source and binary forms, with or without
8
+ # modification, are permitted provided that the following conditions are
9
+ # met:
10
+ #
11
+ # * Redistributions of source code must retain the above copyright
12
+ # notice, this list of conditions and the following disclaimer.
13
+ # * Redistributions in binary form must reproduce the above
14
+ # copyright notice, this list of conditions and the following disclaimer
15
+ # in the documentation and/or other materials provided with the
16
+ # distribution.
17
+ # * Neither the name of Google Inc. nor the names of its
18
+ # contributors may be used to endorse or promote products derived from
19
+ # this software without specific prior written permission.
20
+ #
21
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24
+ # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25
+ # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
+ # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
+ # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28
+ # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29
+ # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30
+ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31
+ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
+
33
+ """Adds support for parameterized tests to Python's unittest TestCase class.
34
+
35
+ A parameterized test is a method in a test case that is invoked with different
36
+ argument tuples.
37
+
38
+ A simple example:
39
+
40
+ class AdditionExample(parameterized.TestCase):
41
+ @parameterized.parameters(
42
+ (1, 2, 3),
43
+ (4, 5, 9),
44
+ (1, 1, 3))
45
+ def testAddition(self, op1, op2, result):
46
+ self.assertEqual(result, op1 + op2)
47
+
48
+
49
+ Each invocation is a separate test case and properly isolated just
50
+ like a normal test method, with its own setUp/tearDown cycle. In the
51
+ example above, there are three separate testcases, one of which will
52
+ fail due to an assertion error (1 + 1 != 3).
53
+
54
+ Parameters for individual test cases can be tuples (with positional parameters)
55
+ or dictionaries (with named parameters):
56
+
57
+ class AdditionExample(parameterized.TestCase):
58
+ @parameterized.parameters(
59
+ {'op1': 1, 'op2': 2, 'result': 3},
60
+ {'op1': 4, 'op2': 5, 'result': 9},
61
+ )
62
+ def testAddition(self, op1, op2, result):
63
+ self.assertEqual(result, op1 + op2)
64
+
65
+ If a parameterized test fails, the error message will show the
66
+ original test name (which is modified internally) and the arguments
67
+ for the specific invocation, which are part of the string returned by
68
+ the shortDescription() method on test cases.
69
+
70
+ The id method of the test, used internally by the unittest framework,
71
+ is also modified to show the arguments. To make sure that test names
72
+ stay the same across several invocations, object representations like
73
+
74
+ >>> class Foo(object):
75
+ ... pass
76
+ >>> repr(Foo())
77
+ '<__main__.Foo object at 0x23d8610>'
78
+
79
+ are turned into '<__main__.Foo>'. For even more descriptive names,
80
+ especially in test logs, you can use the named_parameters decorator. In
81
+ this case, only tuples are supported, and the first parameters has to
82
+ be a string (or an object that returns an apt name when converted via
83
+ str()):
84
+
85
+ class NamedExample(parameterized.TestCase):
86
+ @parameterized.named_parameters(
87
+ ('Normal', 'aa', 'aaa', True),
88
+ ('EmptyPrefix', '', 'abc', True),
89
+ ('BothEmpty', '', '', True))
90
+ def testStartsWith(self, prefix, string, result):
91
+ self.assertEqual(result, strings.startswith(prefix))
92
+
93
+ Named tests also have the benefit that they can be run individually
94
+ from the command line:
95
+
96
+ $ testmodule.py NamedExample.testStartsWithNormal
97
+ .
98
+ --------------------------------------------------------------------
99
+ Ran 1 test in 0.000s
100
+
101
+ OK
102
+
103
+ Parameterized Classes
104
+ =====================
105
+ If invocation arguments are shared across test methods in a single
106
+ TestCase class, instead of decorating all test methods
107
+ individually, the class itself can be decorated:
108
+
109
+ @parameterized.parameters(
110
+ (1, 2, 3)
111
+ (4, 5, 9))
112
+ class ArithmeticTest(parameterized.TestCase):
113
+ def testAdd(self, arg1, arg2, result):
114
+ self.assertEqual(arg1 + arg2, result)
115
+
116
+ def testSubtract(self, arg2, arg2, result):
117
+ self.assertEqual(result - arg1, arg2)
118
+
119
+ Inputs from Iterables
120
+ =====================
121
+ If parameters should be shared across several test cases, or are dynamically
122
+ created from other sources, a single non-tuple iterable can be passed into
123
+ the decorator. This iterable will be used to obtain the test cases:
124
+
125
+ class AdditionExample(parameterized.TestCase):
126
+ @parameterized.parameters(
127
+ c.op1, c.op2, c.result for c in testcases
128
+ )
129
+ def testAddition(self, op1, op2, result):
130
+ self.assertEqual(result, op1 + op2)
131
+
132
+
133
+ Single-Argument Test Methods
134
+ ============================
135
+ If a test method takes only one argument, the single argument does not need to
136
+ be wrapped into a tuple:
137
+
138
+ class NegativeNumberExample(parameterized.TestCase):
139
+ @parameterized.parameters(
140
+ -1, -3, -4, -5
141
+ )
142
+ def testIsNegative(self, arg):
143
+ self.assertTrue(IsNegative(arg))
144
+ """
145
+
146
+ __author__ = 'tmarek@google.com (Torsten Marek)'
147
+
148
+ import functools
149
+ import re
150
+ import types
151
+ import unittest
152
+ import uuid
153
+
154
+ try:
155
+ # Since python 3
156
+ import collections.abc as collections_abc
157
+ except ImportError:
158
+ # Won't work after python 3.8
159
+ import collections as collections_abc
160
+
161
+ ADDR_RE = re.compile(r'\<([a-zA-Z0-9_\-\.]+) object at 0x[a-fA-F0-9]+\>')
162
+ _SEPARATOR = uuid.uuid1().hex
163
+ _FIRST_ARG = object()
164
+ _ARGUMENT_REPR = object()
165
+
166
+
167
+ def _CleanRepr(obj):
168
+ return ADDR_RE.sub(r'<\1>', repr(obj))
169
+
170
+
171
+ # Helper function formerly from the unittest module, removed from it in
172
+ # Python 2.7.
173
+ def _StrClass(cls):
174
+ return '%s.%s' % (cls.__module__, cls.__name__)
175
+
176
+
177
+ def _NonStringIterable(obj):
178
+ return (isinstance(obj, collections_abc.Iterable) and
179
+ not isinstance(obj, str))
180
+
181
+
182
+ def _FormatParameterList(testcase_params):
183
+ if isinstance(testcase_params, collections_abc.Mapping):
184
+ return ', '.join('%s=%s' % (argname, _CleanRepr(value))
185
+ for argname, value in testcase_params.items())
186
+ elif _NonStringIterable(testcase_params):
187
+ return ', '.join(map(_CleanRepr, testcase_params))
188
+ else:
189
+ return _FormatParameterList((testcase_params,))
190
+
191
+
192
+ class _ParameterizedTestIter(object):
193
+ """Callable and iterable class for producing new test cases."""
194
+
195
+ def __init__(self, test_method, testcases, naming_type):
196
+ """Returns concrete test functions for a test and a list of parameters.
197
+
198
+ The naming_type is used to determine the name of the concrete
199
+ functions as reported by the unittest framework. If naming_type is
200
+ _FIRST_ARG, the testcases must be tuples, and the first element must
201
+ have a string representation that is a valid Python identifier.
202
+
203
+ Args:
204
+ test_method: The decorated test method.
205
+ testcases: (list of tuple/dict) A list of parameter
206
+ tuples/dicts for individual test invocations.
207
+ naming_type: The test naming type, either _NAMED or _ARGUMENT_REPR.
208
+ """
209
+ self._test_method = test_method
210
+ self.testcases = testcases
211
+ self._naming_type = naming_type
212
+
213
+ def __call__(self, *args, **kwargs):
214
+ raise RuntimeError('You appear to be running a parameterized test case '
215
+ 'without having inherited from parameterized.'
216
+ 'TestCase. This is bad because none of '
217
+ 'your test cases are actually being run.')
218
+
219
+ def __iter__(self):
220
+ test_method = self._test_method
221
+ naming_type = self._naming_type
222
+
223
+ def MakeBoundParamTest(testcase_params):
224
+ @functools.wraps(test_method)
225
+ def BoundParamTest(self):
226
+ if isinstance(testcase_params, collections_abc.Mapping):
227
+ test_method(self, **testcase_params)
228
+ elif _NonStringIterable(testcase_params):
229
+ test_method(self, *testcase_params)
230
+ else:
231
+ test_method(self, testcase_params)
232
+
233
+ if naming_type is _FIRST_ARG:
234
+ # Signal the metaclass that the name of the test function is unique
235
+ # and descriptive.
236
+ BoundParamTest.__x_use_name__ = True
237
+ BoundParamTest.__name__ += str(testcase_params[0])
238
+ testcase_params = testcase_params[1:]
239
+ elif naming_type is _ARGUMENT_REPR:
240
+ # __x_extra_id__ is used to pass naming information to the __new__
241
+ # method of TestGeneratorMetaclass.
242
+ # The metaclass will make sure to create a unique, but nondescriptive
243
+ # name for this test.
244
+ BoundParamTest.__x_extra_id__ = '(%s)' % (
245
+ _FormatParameterList(testcase_params),)
246
+ else:
247
+ raise RuntimeError('%s is not a valid naming type.' % (naming_type,))
248
+
249
+ BoundParamTest.__doc__ = '%s(%s)' % (
250
+ BoundParamTest.__name__, _FormatParameterList(testcase_params))
251
+ if test_method.__doc__:
252
+ BoundParamTest.__doc__ += '\n%s' % (test_method.__doc__,)
253
+ return BoundParamTest
254
+ return (MakeBoundParamTest(c) for c in self.testcases)
255
+
256
+
257
+ def _IsSingletonList(testcases):
258
+ """True iff testcases contains only a single non-tuple element."""
259
+ return len(testcases) == 1 and not isinstance(testcases[0], tuple)
260
+
261
+
262
+ def _ModifyClass(class_object, testcases, naming_type):
263
+ assert not getattr(class_object, '_id_suffix', None), (
264
+ 'Cannot add parameters to %s,'
265
+ ' which already has parameterized methods.' % (class_object,))
266
+ class_object._id_suffix = id_suffix = {}
267
+ # We change the size of __dict__ while we iterate over it,
268
+ # which Python 3.x will complain about, so use copy().
269
+ for name, obj in class_object.__dict__.copy().items():
270
+ if (name.startswith(unittest.TestLoader.testMethodPrefix)
271
+ and isinstance(obj, types.FunctionType)):
272
+ delattr(class_object, name)
273
+ methods = {}
274
+ _UpdateClassDictForParamTestCase(
275
+ methods, id_suffix, name,
276
+ _ParameterizedTestIter(obj, testcases, naming_type))
277
+ for name, meth in methods.items():
278
+ setattr(class_object, name, meth)
279
+
280
+
281
+ def _ParameterDecorator(naming_type, testcases):
282
+ """Implementation of the parameterization decorators.
283
+
284
+ Args:
285
+ naming_type: The naming type.
286
+ testcases: Testcase parameters.
287
+
288
+ Returns:
289
+ A function for modifying the decorated object.
290
+ """
291
+ def _Apply(obj):
292
+ if isinstance(obj, type):
293
+ _ModifyClass(
294
+ obj,
295
+ list(testcases) if not isinstance(testcases, collections_abc.Sequence)
296
+ else testcases,
297
+ naming_type)
298
+ return obj
299
+ else:
300
+ return _ParameterizedTestIter(obj, testcases, naming_type)
301
+
302
+ if _IsSingletonList(testcases):
303
+ assert _NonStringIterable(testcases[0]), (
304
+ 'Single parameter argument must be a non-string iterable')
305
+ testcases = testcases[0]
306
+
307
+ return _Apply
308
+
309
+
310
+ def parameters(*testcases): # pylint: disable=invalid-name
311
+ """A decorator for creating parameterized tests.
312
+
313
+ See the module docstring for a usage example.
314
+ Args:
315
+ *testcases: Parameters for the decorated method, either a single
316
+ iterable, or a list of tuples/dicts/objects (for tests
317
+ with only one argument).
318
+
319
+ Returns:
320
+ A test generator to be handled by TestGeneratorMetaclass.
321
+ """
322
+ return _ParameterDecorator(_ARGUMENT_REPR, testcases)
323
+
324
+
325
+ def named_parameters(*testcases): # pylint: disable=invalid-name
326
+ """A decorator for creating parameterized tests.
327
+
328
+ See the module docstring for a usage example. The first element of
329
+ each parameter tuple should be a string and will be appended to the
330
+ name of the test method.
331
+
332
+ Args:
333
+ *testcases: Parameters for the decorated method, either a single
334
+ iterable, or a list of tuples.
335
+
336
+ Returns:
337
+ A test generator to be handled by TestGeneratorMetaclass.
338
+ """
339
+ return _ParameterDecorator(_FIRST_ARG, testcases)
340
+
341
+
342
+ class TestGeneratorMetaclass(type):
343
+ """Metaclass for test cases with test generators.
344
+
345
+ A test generator is an iterable in a testcase that produces callables. These
346
+ callables must be single-argument methods. These methods are injected into
347
+ the class namespace and the original iterable is removed. If the name of the
348
+ iterable conforms to the test pattern, the injected methods will be picked
349
+ up as tests by the unittest framework.
350
+
351
+ In general, it is supposed to be used in conjunction with the
352
+ parameters decorator.
353
+ """
354
+
355
+ def __new__(mcs, class_name, bases, dct):
356
+ dct['_id_suffix'] = id_suffix = {}
357
+ for name, obj in dct.copy().items():
358
+ if (name.startswith(unittest.TestLoader.testMethodPrefix) and
359
+ _NonStringIterable(obj)):
360
+ iterator = iter(obj)
361
+ dct.pop(name)
362
+ _UpdateClassDictForParamTestCase(dct, id_suffix, name, iterator)
363
+
364
+ return type.__new__(mcs, class_name, bases, dct)
365
+
366
+
367
+ def _UpdateClassDictForParamTestCase(dct, id_suffix, name, iterator):
368
+ """Adds individual test cases to a dictionary.
369
+
370
+ Args:
371
+ dct: The target dictionary.
372
+ id_suffix: The dictionary for mapping names to test IDs.
373
+ name: The original name of the test case.
374
+ iterator: The iterator generating the individual test cases.
375
+ """
376
+ for idx, func in enumerate(iterator):
377
+ assert callable(func), 'Test generators must yield callables, got %r' % (
378
+ func,)
379
+ if getattr(func, '__x_use_name__', False):
380
+ new_name = func.__name__
381
+ else:
382
+ new_name = '%s%s%d' % (name, _SEPARATOR, idx)
383
+ assert new_name not in dct, (
384
+ 'Name of parameterized test case "%s" not unique' % (new_name,))
385
+ dct[new_name] = func
386
+ id_suffix[new_name] = getattr(func, '__x_extra_id__', '')
387
+
388
+
389
+ class TestCase(unittest.TestCase, metaclass=TestGeneratorMetaclass):
390
+ """Base class for test cases using the parameters decorator."""
391
+
392
+ def _OriginalName(self):
393
+ return self._testMethodName.split(_SEPARATOR)[0]
394
+
395
+ def __str__(self):
396
+ return '%s (%s)' % (self._OriginalName(), _StrClass(self.__class__))
397
+
398
+ def id(self): # pylint: disable=invalid-name
399
+ """Returns the descriptive ID of the test.
400
+
401
+ This is used internally by the unittesting framework to get a name
402
+ for the test to be used in reports.
403
+
404
+ Returns:
405
+ The test id.
406
+ """
407
+ return '%s.%s%s' % (_StrClass(self.__class__),
408
+ self._OriginalName(),
409
+ self._id_suffix.get(self._testMethodName, ''))
410
+
411
+
412
+ def CoopTestCase(other_base_class):
413
+ """Returns a new base class with a cooperative metaclass base.
414
+
415
+ This enables the TestCase to be used in combination
416
+ with other base classes that have custom metaclasses, such as
417
+ mox.MoxTestBase.
418
+
419
+ Only works with metaclasses that do not override type.__new__.
420
+
421
+ Example:
422
+
423
+ import google3
424
+ import mox
425
+
426
+ from google3.testing.pybase import parameterized
427
+
428
+ class ExampleTest(parameterized.CoopTestCase(mox.MoxTestBase)):
429
+ ...
430
+
431
+ Args:
432
+ other_base_class: (class) A test case base class.
433
+
434
+ Returns:
435
+ A new class object.
436
+ """
437
+ metaclass = type(
438
+ 'CoopMetaclass',
439
+ (other_base_class.__metaclass__,
440
+ TestGeneratorMetaclass), {})
441
+ return metaclass(
442
+ 'CoopTestCase',
443
+ (other_base_class, TestCase), {})
@@ -0,0 +1,168 @@
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
+
31
+ """Determine which implementation of the protobuf API is used in this process.
32
+ """
33
+
34
+ import importlib
35
+ import os
36
+ import sys
37
+ import warnings
38
+
39
+
40
+ def _ApiVersionToImplementationType(api_version):
41
+ if api_version == 2:
42
+ return 'cpp'
43
+ if api_version == 1:
44
+ raise ValueError('api_version=1 is no longer supported.')
45
+ if api_version == 0:
46
+ return 'python'
47
+ return None
48
+
49
+
50
+ _implementation_type = None
51
+ try:
52
+ # pylint: disable=g-import-not-at-top
53
+ from google.protobuf_ml.internal import _api_implementation
54
+ # The compile-time constants in the _api_implementation module can be used to
55
+ # switch to a certain implementation of the Python API at build time.
56
+ _implementation_type = _ApiVersionToImplementationType(
57
+ _api_implementation.api_version)
58
+ except ImportError:
59
+ pass # Unspecified by compiler flags.
60
+
61
+
62
+ def _CanImport(mod_name):
63
+ try:
64
+ mod = importlib.import_module(mod_name)
65
+ # Work around a known issue in the classic bootstrap .par import hook.
66
+ if not mod:
67
+ raise ImportError(mod_name + ' import succeeded but was None')
68
+ return True
69
+ except ImportError:
70
+ return False
71
+
72
+
73
+ if _implementation_type is None:
74
+ if _CanImport('google._upb._message'):
75
+ _implementation_type = 'upb'
76
+ elif _CanImport('google.protobuf_ml.pyext._message'):
77
+ _implementation_type = 'cpp'
78
+ else:
79
+ _implementation_type = 'python'
80
+
81
+
82
+ # This environment variable can be used to switch to a certain implementation
83
+ # of the Python API, overriding the compile-time constants in the
84
+ # _api_implementation module. Right now only 'python', 'cpp' and 'upb' are
85
+ # valid values. Any other value will raise error.
86
+ _implementation_type = os.getenv('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION',
87
+ _implementation_type)
88
+
89
+ if _implementation_type not in ('python', 'cpp', 'upb'):
90
+ raise ValueError('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION {0} is not '
91
+ 'supported. Please set to \'python\', \'cpp\' or '
92
+ '\'upb\'.'.format(_implementation_type))
93
+
94
+ if 'PyPy' in sys.version and _implementation_type == 'cpp':
95
+ warnings.warn('PyPy does not work yet with cpp protocol buffers. '
96
+ 'Falling back to the python implementation.')
97
+ _implementation_type = 'python'
98
+
99
+ _c_module = None
100
+
101
+ if _implementation_type == 'cpp':
102
+ try:
103
+ # pylint: disable=g-import-not-at-top
104
+ from google.protobuf_ml.pyext import _message
105
+ _c_module = _message
106
+ del _message
107
+ except ImportError:
108
+ # TODO(jieluo): fail back to python
109
+ warnings.warn(
110
+ 'Selected implementation cpp is not available.')
111
+ pass
112
+
113
+ if _implementation_type == 'upb':
114
+ try:
115
+ # pylint: disable=g-import-not-at-top
116
+ from google._upb import _message
117
+ _c_module = _message
118
+ del _message
119
+ except ImportError:
120
+ warnings.warn('Selected implementation upb is not available. '
121
+ 'Falling back to the python implementation.')
122
+ _implementation_type = 'python'
123
+ pass
124
+
125
+ # Detect if serialization should be deterministic by default
126
+ try:
127
+ # The presence of this module in a build allows the proto implementation to
128
+ # be upgraded merely via build deps.
129
+ #
130
+ # NOTE: Merely importing this automatically enables deterministic proto
131
+ # serialization for C++ code, but we still need to export it as a boolean so
132
+ # that we can do the same for `_implementation_type == 'python'`.
133
+ #
134
+ # NOTE2: It is possible for C++ code to enable deterministic serialization by
135
+ # default _without_ affecting Python code, if the C++ implementation is not in
136
+ # use by this module. That is intended behavior, so we don't actually expose
137
+ # this boolean outside of this module.
138
+ #
139
+ # pylint: disable=g-import-not-at-top,unused-import
140
+ from google.protobuf_ml import enable_deterministic_proto_serialization
141
+ _python_deterministic_proto_serialization = True
142
+ except ImportError:
143
+ _python_deterministic_proto_serialization = False
144
+
145
+
146
+ # Usage of this function is discouraged. Clients shouldn't care which
147
+ # implementation of the API is in use. Note that there is no guarantee
148
+ # that differences between APIs will be maintained.
149
+ # Please don't use this function if possible.
150
+ def Type():
151
+ return _implementation_type
152
+
153
+
154
+ def _SetType(implementation_type):
155
+ """Never use! Only for protobuf benchmark."""
156
+ global _implementation_type
157
+ _implementation_type = implementation_type
158
+
159
+
160
+ # See comment on 'Type' above.
161
+ # TODO(jieluo): Remove the API, it returns a constant. b/228102101
162
+ def Version():
163
+ return 2
164
+
165
+
166
+ # For internal use only
167
+ def IsPythonDefaultSerializationDeterministic():
168
+ return _python_deterministic_proto_serialization