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
@@ -0,0 +1,708 @@
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
+ """Contains container classes to represent different protocol buffer types.
32
+
33
+ This file defines container classes which represent categories of protocol
34
+ buffer field types which need extra maintenance. Currently these categories
35
+ are:
36
+
37
+ - Repeated scalar fields - These are all repeated fields which aren't
38
+ composite (e.g. they are of simple types like int32, string, etc).
39
+ - Repeated composite fields - Repeated fields which are composite. This
40
+ includes groups and nested messages.
41
+ """
42
+
43
+ import collections.abc
44
+ import copy
45
+ import pickle
46
+ from typing import (
47
+ Any,
48
+ Iterable,
49
+ Iterator,
50
+ List,
51
+ MutableMapping,
52
+ MutableSequence,
53
+ NoReturn,
54
+ Optional,
55
+ Sequence,
56
+ TypeVar,
57
+ Union,
58
+ overload,
59
+ )
60
+
61
+ _T = TypeVar('_T')
62
+ _K = TypeVar('_K')
63
+ _V = TypeVar('_V')
64
+
65
+ class BaseContainer(Sequence[_T]):
66
+ """Base container class."""
67
+
68
+ # Minimizes memory usage and disallows assignment to other attributes.
69
+ __slots__ = ['_message_listener', '_values']
70
+
71
+ def __init__(self, message_listener: Any) -> None:
72
+ """
73
+ Args:
74
+ message_listener: A MessageListener implementation.
75
+ The RepeatedScalarFieldContainer will call this object's
76
+ Modified() method when it is modified.
77
+ """
78
+ self._message_listener = message_listener
79
+ self._values = []
80
+
81
+ @overload
82
+ def __getitem__(self, key: int) -> _T:
83
+ ...
84
+
85
+ @overload
86
+ def __getitem__(self, key: slice) -> List[_T]:
87
+ ...
88
+
89
+ def __getitem__(self, key):
90
+ """Retrieves item by the specified key."""
91
+ return self._values[key]
92
+
93
+ def __len__(self) -> int:
94
+ """Returns the number of elements in the container."""
95
+ return len(self._values)
96
+
97
+ def __ne__(self, other: Any) -> bool:
98
+ """Checks if another instance isn't equal to this one."""
99
+ # The concrete classes should define __eq__.
100
+ return not self == other
101
+
102
+ __hash__ = None
103
+
104
+ def __repr__(self) -> str:
105
+ return repr(self._values)
106
+
107
+ def sort(self, *args, **kwargs) -> None:
108
+ # Continue to support the old sort_function keyword argument.
109
+ # This is expected to be a rare occurrence, so use LBYL to avoid
110
+ # the overhead of actually catching KeyError.
111
+ if 'sort_function' in kwargs:
112
+ kwargs['cmp'] = kwargs.pop('sort_function')
113
+ self._values.sort(*args, **kwargs)
114
+
115
+ def reverse(self) -> None:
116
+ self._values.reverse()
117
+
118
+
119
+ # TODO(slebedev): Remove this. BaseContainer does *not* conform to
120
+ # MutableSequence, only its subclasses do.
121
+ collections.abc.MutableSequence.register(BaseContainer)
122
+
123
+
124
+ class RepeatedScalarFieldContainer(BaseContainer[_T], MutableSequence[_T]):
125
+ """Simple, type-checked, list-like container for holding repeated scalars."""
126
+
127
+ # Disallows assignment to other attributes.
128
+ __slots__ = ['_type_checker']
129
+
130
+ def __init__(
131
+ self,
132
+ message_listener: Any,
133
+ type_checker: Any,
134
+ ) -> None:
135
+ """Args:
136
+
137
+ message_listener: A MessageListener implementation. The
138
+ RepeatedScalarFieldContainer will call this object's Modified() method
139
+ when it is modified.
140
+ type_checker: A type_checkers.ValueChecker instance to run on elements
141
+ inserted into this container.
142
+ """
143
+ super().__init__(message_listener)
144
+ self._type_checker = type_checker
145
+
146
+ def append(self, value: _T) -> None:
147
+ """Appends an item to the list. Similar to list.append()."""
148
+ self._values.append(self._type_checker.CheckValue(value))
149
+ if not self._message_listener.dirty:
150
+ self._message_listener.Modified()
151
+
152
+ def insert(self, key: int, value: _T) -> None:
153
+ """Inserts the item at the specified position. Similar to list.insert()."""
154
+ self._values.insert(key, self._type_checker.CheckValue(value))
155
+ if not self._message_listener.dirty:
156
+ self._message_listener.Modified()
157
+
158
+ def extend(self, elem_seq: Iterable[_T]) -> None:
159
+ """Extends by appending the given iterable. Similar to list.extend()."""
160
+ if elem_seq is None:
161
+ return
162
+ try:
163
+ elem_seq_iter = iter(elem_seq)
164
+ except TypeError:
165
+ if not elem_seq:
166
+ # silently ignore falsy inputs :-/.
167
+ # TODO(ptucker): Deprecate this behavior. b/18413862
168
+ return
169
+ raise
170
+
171
+ new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter]
172
+ if new_values:
173
+ self._values.extend(new_values)
174
+ self._message_listener.Modified()
175
+
176
+ def MergeFrom(
177
+ self,
178
+ other: Union['RepeatedScalarFieldContainer[_T]', Iterable[_T]],
179
+ ) -> None:
180
+ """Appends the contents of another repeated field of the same type to this
181
+ one. We do not check the types of the individual fields.
182
+ """
183
+ self._values.extend(other)
184
+ self._message_listener.Modified()
185
+
186
+ def remove(self, elem: _T):
187
+ """Removes an item from the list. Similar to list.remove()."""
188
+ self._values.remove(elem)
189
+ self._message_listener.Modified()
190
+
191
+ def pop(self, key: Optional[int] = -1) -> _T:
192
+ """Removes and returns an item at a given index. Similar to list.pop()."""
193
+ value = self._values[key]
194
+ self.__delitem__(key)
195
+ return value
196
+
197
+ @overload
198
+ def __setitem__(self, key: int, value: _T) -> None:
199
+ ...
200
+
201
+ @overload
202
+ def __setitem__(self, key: slice, value: Iterable[_T]) -> None:
203
+ ...
204
+
205
+ def __setitem__(self, key, value) -> None:
206
+ """Sets the item on the specified position."""
207
+ if isinstance(key, slice):
208
+ if key.step is not None:
209
+ raise ValueError('Extended slices not supported')
210
+ self._values[key] = map(self._type_checker.CheckValue, value)
211
+ self._message_listener.Modified()
212
+ else:
213
+ self._values[key] = self._type_checker.CheckValue(value)
214
+ self._message_listener.Modified()
215
+
216
+ def __delitem__(self, key: Union[int, slice]) -> None:
217
+ """Deletes the item at the specified position."""
218
+ del self._values[key]
219
+ self._message_listener.Modified()
220
+
221
+ def __eq__(self, other: Any) -> bool:
222
+ """Compares the current instance with another one."""
223
+ if self is other:
224
+ return True
225
+ # Special case for the same type which should be common and fast.
226
+ if isinstance(other, self.__class__):
227
+ return other._values == self._values
228
+ # We are presumably comparing against some other sequence type.
229
+ return other == self._values
230
+
231
+ def __deepcopy__(
232
+ self,
233
+ unused_memo: Any = None,
234
+ ) -> 'RepeatedScalarFieldContainer[_T]':
235
+ clone = RepeatedScalarFieldContainer(
236
+ copy.deepcopy(self._message_listener), self._type_checker)
237
+ clone.MergeFrom(self)
238
+ return clone
239
+
240
+ def __reduce__(self, **kwargs) -> NoReturn:
241
+ raise pickle.PickleError(
242
+ "Can't pickle repeated scalar fields, convert to list first")
243
+
244
+
245
+ # TODO(slebedev): Constrain T to be a subtype of Message.
246
+ class RepeatedCompositeFieldContainer(BaseContainer[_T], MutableSequence[_T]):
247
+ """Simple, list-like container for holding repeated composite fields."""
248
+
249
+ # Disallows assignment to other attributes.
250
+ __slots__ = ['_message_descriptor']
251
+
252
+ def __init__(self, message_listener: Any, message_descriptor: Any) -> None:
253
+ """
254
+ Note that we pass in a descriptor instead of the generated directly,
255
+ since at the time we construct a _RepeatedCompositeFieldContainer we
256
+ haven't yet necessarily initialized the type that will be contained in the
257
+ container.
258
+
259
+ Args:
260
+ message_listener: A MessageListener implementation.
261
+ The RepeatedCompositeFieldContainer will call this object's
262
+ Modified() method when it is modified.
263
+ message_descriptor: A Descriptor instance describing the protocol type
264
+ that should be present in this container. We'll use the
265
+ _concrete_class field of this descriptor when the client calls add().
266
+ """
267
+ super().__init__(message_listener)
268
+ self._message_descriptor = message_descriptor
269
+
270
+ def add(self, **kwargs: Any) -> _T:
271
+ """Adds a new element at the end of the list and returns it. Keyword
272
+ arguments may be used to initialize the element.
273
+ """
274
+ new_element = self._message_descriptor._concrete_class(**kwargs)
275
+ new_element._SetListener(self._message_listener)
276
+ self._values.append(new_element)
277
+ if not self._message_listener.dirty:
278
+ self._message_listener.Modified()
279
+ return new_element
280
+
281
+ def append(self, value: _T) -> None:
282
+ """Appends one element by copying the message."""
283
+ new_element = self._message_descriptor._concrete_class()
284
+ new_element._SetListener(self._message_listener)
285
+ new_element.CopyFrom(value)
286
+ self._values.append(new_element)
287
+ if not self._message_listener.dirty:
288
+ self._message_listener.Modified()
289
+
290
+ def insert(self, key: int, value: _T) -> None:
291
+ """Inserts the item at the specified position by copying."""
292
+ new_element = self._message_descriptor._concrete_class()
293
+ new_element._SetListener(self._message_listener)
294
+ new_element.CopyFrom(value)
295
+ self._values.insert(key, new_element)
296
+ if not self._message_listener.dirty:
297
+ self._message_listener.Modified()
298
+
299
+ def extend(self, elem_seq: Iterable[_T]) -> None:
300
+ """Extends by appending the given sequence of elements of the same type
301
+
302
+ as this one, copying each individual message.
303
+ """
304
+ message_class = self._message_descriptor._concrete_class
305
+ listener = self._message_listener
306
+ values = self._values
307
+ for message in elem_seq:
308
+ new_element = message_class()
309
+ new_element._SetListener(listener)
310
+ new_element.MergeFrom(message)
311
+ values.append(new_element)
312
+ listener.Modified()
313
+
314
+ def MergeFrom(
315
+ self,
316
+ other: Union['RepeatedCompositeFieldContainer[_T]', Iterable[_T]],
317
+ ) -> None:
318
+ """Appends the contents of another repeated field of the same type to this
319
+ one, copying each individual message.
320
+ """
321
+ self.extend(other)
322
+
323
+ def remove(self, elem: _T) -> None:
324
+ """Removes an item from the list. Similar to list.remove()."""
325
+ self._values.remove(elem)
326
+ self._message_listener.Modified()
327
+
328
+ def pop(self, key: Optional[int] = -1) -> _T:
329
+ """Removes and returns an item at a given index. Similar to list.pop()."""
330
+ value = self._values[key]
331
+ self.__delitem__(key)
332
+ return value
333
+
334
+ @overload
335
+ def __setitem__(self, key: int, value: _T) -> None:
336
+ ...
337
+
338
+ @overload
339
+ def __setitem__(self, key: slice, value: Iterable[_T]) -> None:
340
+ ...
341
+
342
+ def __setitem__(self, key, value):
343
+ # This method is implemented to make RepeatedCompositeFieldContainer
344
+ # structurally compatible with typing.MutableSequence. It is
345
+ # otherwise unsupported and will always raise an error.
346
+ raise TypeError(
347
+ f'{self.__class__.__name__} object does not support item assignment')
348
+
349
+ def __delitem__(self, key: Union[int, slice]) -> None:
350
+ """Deletes the item at the specified position."""
351
+ del self._values[key]
352
+ self._message_listener.Modified()
353
+
354
+ def __eq__(self, other: Any) -> bool:
355
+ """Compares the current instance with another one."""
356
+ if self is other:
357
+ return True
358
+ if not isinstance(other, self.__class__):
359
+ raise TypeError('Can only compare repeated composite fields against '
360
+ 'other repeated composite fields.')
361
+ return self._values == other._values
362
+
363
+
364
+ class ScalarMap(MutableMapping[_K, _V]):
365
+ """Simple, type-checked, dict-like container for holding repeated scalars."""
366
+
367
+ # Disallows assignment to other attributes.
368
+ __slots__ = ['_key_checker', '_value_checker', '_values', '_message_listener',
369
+ '_entry_descriptor']
370
+
371
+ def __init__(
372
+ self,
373
+ message_listener: Any,
374
+ key_checker: Any,
375
+ value_checker: Any,
376
+ entry_descriptor: Any,
377
+ ) -> None:
378
+ """
379
+ Args:
380
+ message_listener: A MessageListener implementation.
381
+ The ScalarMap will call this object's Modified() method when it
382
+ is modified.
383
+ key_checker: A type_checkers.ValueChecker instance to run on keys
384
+ inserted into this container.
385
+ value_checker: A type_checkers.ValueChecker instance to run on values
386
+ inserted into this container.
387
+ entry_descriptor: The MessageDescriptor of a map entry: key and value.
388
+ """
389
+ self._message_listener = message_listener
390
+ self._key_checker = key_checker
391
+ self._value_checker = value_checker
392
+ self._entry_descriptor = entry_descriptor
393
+ self._values = {}
394
+
395
+ def __getitem__(self, key: _K) -> _V:
396
+ try:
397
+ return self._values[key]
398
+ except KeyError:
399
+ key = self._key_checker.CheckValue(key)
400
+ val = self._value_checker.DefaultValue()
401
+ self._values[key] = val
402
+ return val
403
+
404
+ def __contains__(self, item: _K) -> bool:
405
+ # We check the key's type to match the strong-typing flavor of the API.
406
+ # Also this makes it easier to match the behavior of the C++ implementation.
407
+ self._key_checker.CheckValue(item)
408
+ return item in self._values
409
+
410
+ @overload
411
+ def get(self, key: _K) -> Optional[_V]:
412
+ ...
413
+
414
+ @overload
415
+ def get(self, key: _K, default: _T) -> Union[_V, _T]:
416
+ ...
417
+
418
+ # We need to override this explicitly, because our defaultdict-like behavior
419
+ # will make the default implementation (from our base class) always insert
420
+ # the key.
421
+ def get(self, key, default=None):
422
+ if key in self:
423
+ return self[key]
424
+ else:
425
+ return default
426
+
427
+ def __setitem__(self, key: _K, value: _V) -> _T:
428
+ checked_key = self._key_checker.CheckValue(key)
429
+ checked_value = self._value_checker.CheckValue(value)
430
+ self._values[checked_key] = checked_value
431
+ self._message_listener.Modified()
432
+
433
+ def __delitem__(self, key: _K) -> None:
434
+ del self._values[key]
435
+ self._message_listener.Modified()
436
+
437
+ def __len__(self) -> int:
438
+ return len(self._values)
439
+
440
+ def __iter__(self) -> Iterator[_K]:
441
+ return iter(self._values)
442
+
443
+ def __repr__(self) -> str:
444
+ return repr(self._values)
445
+
446
+ def MergeFrom(self, other: 'ScalarMap[_K, _V]') -> None:
447
+ self._values.update(other._values)
448
+ self._message_listener.Modified()
449
+
450
+ def InvalidateIterators(self) -> None:
451
+ # It appears that the only way to reliably invalidate iterators to
452
+ # self._values is to ensure that its size changes.
453
+ original = self._values
454
+ self._values = original.copy()
455
+ original[None] = None
456
+
457
+ # This is defined in the abstract base, but we can do it much more cheaply.
458
+ def clear(self) -> None:
459
+ self._values.clear()
460
+ self._message_listener.Modified()
461
+
462
+ def GetEntryClass(self) -> Any:
463
+ return self._entry_descriptor._concrete_class
464
+
465
+
466
+ class MessageMap(MutableMapping[_K, _V]):
467
+ """Simple, type-checked, dict-like container for with submessage values."""
468
+
469
+ # Disallows assignment to other attributes.
470
+ __slots__ = ['_key_checker', '_values', '_message_listener',
471
+ '_message_descriptor', '_entry_descriptor']
472
+
473
+ def __init__(
474
+ self,
475
+ message_listener: Any,
476
+ message_descriptor: Any,
477
+ key_checker: Any,
478
+ entry_descriptor: Any,
479
+ ) -> None:
480
+ """
481
+ Args:
482
+ message_listener: A MessageListener implementation.
483
+ The ScalarMap will call this object's Modified() method when it
484
+ is modified.
485
+ key_checker: A type_checkers.ValueChecker instance to run on keys
486
+ inserted into this container.
487
+ value_checker: A type_checkers.ValueChecker instance to run on values
488
+ inserted into this container.
489
+ entry_descriptor: The MessageDescriptor of a map entry: key and value.
490
+ """
491
+ self._message_listener = message_listener
492
+ self._message_descriptor = message_descriptor
493
+ self._key_checker = key_checker
494
+ self._entry_descriptor = entry_descriptor
495
+ self._values = {}
496
+
497
+ def __getitem__(self, key: _K) -> _V:
498
+ key = self._key_checker.CheckValue(key)
499
+ try:
500
+ return self._values[key]
501
+ except KeyError:
502
+ new_element = self._message_descriptor._concrete_class()
503
+ new_element._SetListener(self._message_listener)
504
+ self._values[key] = new_element
505
+ self._message_listener.Modified()
506
+ return new_element
507
+
508
+ def get_or_create(self, key: _K) -> _V:
509
+ """get_or_create() is an alias for getitem (ie. map[key]).
510
+
511
+ Args:
512
+ key: The key to get or create in the map.
513
+
514
+ This is useful in cases where you want to be explicit that the call is
515
+ mutating the map. This can avoid lint errors for statements like this
516
+ that otherwise would appear to be pointless statements:
517
+
518
+ msg.my_map[key]
519
+ """
520
+ return self[key]
521
+
522
+ @overload
523
+ def get(self, key: _K) -> Optional[_V]:
524
+ ...
525
+
526
+ @overload
527
+ def get(self, key: _K, default: _T) -> Union[_V, _T]:
528
+ ...
529
+
530
+ # We need to override this explicitly, because our defaultdict-like behavior
531
+ # will make the default implementation (from our base class) always insert
532
+ # the key.
533
+ def get(self, key, default=None):
534
+ if key in self:
535
+ return self[key]
536
+ else:
537
+ return default
538
+
539
+ def __contains__(self, item: _K) -> bool:
540
+ item = self._key_checker.CheckValue(item)
541
+ return item in self._values
542
+
543
+ def __setitem__(self, key: _K, value: _V) -> NoReturn:
544
+ raise ValueError('May not set values directly, call my_map[key].foo = 5')
545
+
546
+ def __delitem__(self, key: _K) -> None:
547
+ key = self._key_checker.CheckValue(key)
548
+ del self._values[key]
549
+ self._message_listener.Modified()
550
+
551
+ def __len__(self) -> int:
552
+ return len(self._values)
553
+
554
+ def __iter__(self) -> Iterator[_K]:
555
+ return iter(self._values)
556
+
557
+ def __repr__(self) -> str:
558
+ return repr(self._values)
559
+
560
+ def MergeFrom(self, other: 'MessageMap[_K, _V]') -> None:
561
+ # pylint: disable=protected-access
562
+ for key in other._values:
563
+ # According to documentation: "When parsing from the wire or when merging,
564
+ # if there are duplicate map keys the last key seen is used".
565
+ if key in self:
566
+ del self[key]
567
+ self[key].CopyFrom(other[key])
568
+ # self._message_listener.Modified() not required here, because
569
+ # mutations to submessages already propagate.
570
+
571
+ def InvalidateIterators(self) -> None:
572
+ # It appears that the only way to reliably invalidate iterators to
573
+ # self._values is to ensure that its size changes.
574
+ original = self._values
575
+ self._values = original.copy()
576
+ original[None] = None
577
+
578
+ # This is defined in the abstract base, but we can do it much more cheaply.
579
+ def clear(self) -> None:
580
+ self._values.clear()
581
+ self._message_listener.Modified()
582
+
583
+ def GetEntryClass(self) -> Any:
584
+ return self._entry_descriptor._concrete_class
585
+
586
+
587
+ class _UnknownField:
588
+ """A parsed unknown field."""
589
+
590
+ # Disallows assignment to other attributes.
591
+ __slots__ = ['_field_number', '_wire_type', '_data']
592
+
593
+ def __init__(self, field_number, wire_type, data):
594
+ self._field_number = field_number
595
+ self._wire_type = wire_type
596
+ self._data = data
597
+ return
598
+
599
+ def __lt__(self, other):
600
+ # pylint: disable=protected-access
601
+ return self._field_number < other._field_number
602
+
603
+ def __eq__(self, other):
604
+ if self is other:
605
+ return True
606
+ # pylint: disable=protected-access
607
+ return (self._field_number == other._field_number and
608
+ self._wire_type == other._wire_type and
609
+ self._data == other._data)
610
+
611
+
612
+ class UnknownFieldRef: # pylint: disable=missing-class-docstring
613
+
614
+ def __init__(self, parent, index):
615
+ self._parent = parent
616
+ self._index = index
617
+
618
+ def _check_valid(self):
619
+ if not self._parent:
620
+ raise ValueError('UnknownField does not exist. '
621
+ 'The parent message might be cleared.')
622
+ if self._index >= len(self._parent):
623
+ raise ValueError('UnknownField does not exist. '
624
+ 'The parent message might be cleared.')
625
+
626
+ @property
627
+ def field_number(self):
628
+ self._check_valid()
629
+ # pylint: disable=protected-access
630
+ return self._parent._internal_get(self._index)._field_number
631
+
632
+ @property
633
+ def wire_type(self):
634
+ self._check_valid()
635
+ # pylint: disable=protected-access
636
+ return self._parent._internal_get(self._index)._wire_type
637
+
638
+ @property
639
+ def data(self):
640
+ self._check_valid()
641
+ # pylint: disable=protected-access
642
+ return self._parent._internal_get(self._index)._data
643
+
644
+
645
+ class UnknownFieldSet:
646
+ """UnknownField container"""
647
+
648
+ # Disallows assignment to other attributes.
649
+ __slots__ = ['_values']
650
+
651
+ def __init__(self):
652
+ self._values = []
653
+
654
+ def __getitem__(self, index):
655
+ if self._values is None:
656
+ raise ValueError('UnknownFields does not exist. '
657
+ 'The parent message might be cleared.')
658
+ size = len(self._values)
659
+ if index < 0:
660
+ index += size
661
+ if index < 0 or index >= size:
662
+ raise IndexError('index %d out of range'.index)
663
+
664
+ return UnknownFieldRef(self, index)
665
+
666
+ def _internal_get(self, index):
667
+ return self._values[index]
668
+
669
+ def __len__(self):
670
+ if self._values is None:
671
+ raise ValueError('UnknownFields does not exist. '
672
+ 'The parent message might be cleared.')
673
+ return len(self._values)
674
+
675
+ def _add(self, field_number, wire_type, data):
676
+ unknown_field = _UnknownField(field_number, wire_type, data)
677
+ self._values.append(unknown_field)
678
+ return unknown_field
679
+
680
+ def __iter__(self):
681
+ for i in range(len(self)):
682
+ yield UnknownFieldRef(self, i)
683
+
684
+ def _extend(self, other):
685
+ if other is None:
686
+ return
687
+ # pylint: disable=protected-access
688
+ self._values.extend(other._values)
689
+
690
+ def __eq__(self, other):
691
+ if self is other:
692
+ return True
693
+ # Sort unknown fields because their order shouldn't
694
+ # affect equality test.
695
+ values = list(self._values)
696
+ if other is None:
697
+ return not values
698
+ values.sort()
699
+ # pylint: disable=protected-access
700
+ other_values = sorted(other._values)
701
+ return values == other_values
702
+
703
+ def _clear(self):
704
+ for value in self._values:
705
+ # pylint: disable=protected-access
706
+ if isinstance(value._data, UnknownFieldSet):
707
+ value._data._clear() # pylint: disable=protected-access
708
+ self._values = None