Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/protobuf/message.py: 49%
90 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 07:30 +0000
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 07:30 +0000
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.
31# TODO(robinson): We should just make these methods all "pure-virtual" and move
32# all implementation out, into reflection.py for now.
35"""Contains an abstract base class for protocol messages."""
37__author__ = 'robinson@google.com (Will Robinson)'
39class Error(Exception):
40 """Base error type for this module."""
41 pass
44class DecodeError(Error):
45 """Exception raised when deserializing messages."""
46 pass
49class EncodeError(Error):
50 """Exception raised when serializing messages."""
51 pass
54class Message(object):
56 """Abstract base class for protocol messages.
58 Protocol message classes are almost always generated by the protocol
59 compiler. These generated types subclass Message and implement the methods
60 shown below.
61 """
63 # TODO(robinson): Link to an HTML document here.
65 # TODO(robinson): Document that instances of this class will also
66 # have an Extensions attribute with __getitem__ and __setitem__.
67 # Again, not sure how to best convey this.
69 # TODO(robinson): Document that the class must also have a static
70 # RegisterExtension(extension_field) method.
71 # Not sure how to best express at this point.
73 # TODO(robinson): Document these fields and methods.
75 __slots__ = []
77 #: The :class:`google.protobuf.Descriptor`
78 # for this message type.
79 DESCRIPTOR = None
81 def __deepcopy__(self, memo=None):
82 clone = type(self)()
83 clone.MergeFrom(self)
84 return clone
86 def __eq__(self, other_msg):
87 """Recursively compares two messages by value and structure."""
88 raise NotImplementedError
90 def __ne__(self, other_msg):
91 # Can't just say self != other_msg, since that would infinitely recurse. :)
92 return not self == other_msg
94 def __hash__(self):
95 raise TypeError('unhashable object')
97 def __str__(self):
98 """Outputs a human-readable representation of the message."""
99 raise NotImplementedError
101 def __unicode__(self):
102 """Outputs a human-readable representation of the message."""
103 raise NotImplementedError
105 def MergeFrom(self, other_msg):
106 """Merges the contents of the specified message into current message.
108 This method merges the contents of the specified message into the current
109 message. Singular fields that are set in the specified message overwrite
110 the corresponding fields in the current message. Repeated fields are
111 appended. Singular sub-messages and groups are recursively merged.
113 Args:
114 other_msg (Message): A message to merge into the current message.
115 """
116 raise NotImplementedError
118 def CopyFrom(self, other_msg):
119 """Copies the content of the specified message into the current message.
121 The method clears the current message and then merges the specified
122 message using MergeFrom.
124 Args:
125 other_msg (Message): A message to copy into the current one.
126 """
127 if self is other_msg:
128 return
129 self.Clear()
130 self.MergeFrom(other_msg)
132 def Clear(self):
133 """Clears all data that was set in the message."""
134 raise NotImplementedError
136 def SetInParent(self):
137 """Mark this as present in the parent.
139 This normally happens automatically when you assign a field of a
140 sub-message, but sometimes you want to make the sub-message
141 present while keeping it empty. If you find yourself using this,
142 you may want to reconsider your design.
143 """
144 raise NotImplementedError
146 def IsInitialized(self):
147 """Checks if the message is initialized.
149 Returns:
150 bool: The method returns True if the message is initialized (i.e. all of
151 its required fields are set).
152 """
153 raise NotImplementedError
155 # TODO(robinson): MergeFromString() should probably return None and be
156 # implemented in terms of a helper that returns the # of bytes read. Our
157 # deserialization routines would use the helper when recursively
158 # deserializing, but the end user would almost always just want the no-return
159 # MergeFromString().
161 def MergeFromString(self, serialized):
162 """Merges serialized protocol buffer data into this message.
164 When we find a field in `serialized` that is already present
165 in this message:
167 - If it's a "repeated" field, we append to the end of our list.
168 - Else, if it's a scalar, we overwrite our field.
169 - Else, (it's a nonrepeated composite), we recursively merge
170 into the existing composite.
172 Args:
173 serialized (bytes): Any object that allows us to call
174 ``memoryview(serialized)`` to access a string of bytes using the
175 buffer interface.
177 Returns:
178 int: The number of bytes read from `serialized`.
179 For non-group messages, this will always be `len(serialized)`,
180 but for messages which are actually groups, this will
181 generally be less than `len(serialized)`, since we must
182 stop when we reach an ``END_GROUP`` tag. Note that if
183 we *do* stop because of an ``END_GROUP`` tag, the number
184 of bytes returned does not include the bytes
185 for the ``END_GROUP`` tag information.
187 Raises:
188 DecodeError: if the input cannot be parsed.
189 """
190 # TODO(robinson): Document handling of unknown fields.
191 # TODO(robinson): When we switch to a helper, this will return None.
192 raise NotImplementedError
194 def ParseFromString(self, serialized):
195 """Parse serialized protocol buffer data in binary form into this message.
197 Like :func:`MergeFromString()`, except we clear the object first.
199 Raises:
200 message.DecodeError if the input cannot be parsed.
201 """
202 self.Clear()
203 return self.MergeFromString(serialized)
205 def SerializeToString(self, **kwargs):
206 """Serializes the protocol message to a binary string.
208 Keyword Args:
209 deterministic (bool): If true, requests deterministic serialization
210 of the protobuf, with predictable ordering of map keys.
212 Returns:
213 A binary string representation of the message if all of the required
214 fields in the message are set (i.e. the message is initialized).
216 Raises:
217 EncodeError: if the message isn't initialized (see :func:`IsInitialized`).
218 """
219 raise NotImplementedError
221 def SerializePartialToString(self, **kwargs):
222 """Serializes the protocol message to a binary string.
224 This method is similar to SerializeToString but doesn't check if the
225 message is initialized.
227 Keyword Args:
228 deterministic (bool): If true, requests deterministic serialization
229 of the protobuf, with predictable ordering of map keys.
231 Returns:
232 bytes: A serialized representation of the partial message.
233 """
234 raise NotImplementedError
236 # TODO(robinson): Decide whether we like these better
237 # than auto-generated has_foo() and clear_foo() methods
238 # on the instances themselves. This way is less consistent
239 # with C++, but it makes reflection-type access easier and
240 # reduces the number of magically autogenerated things.
241 #
242 # TODO(robinson): Be sure to document (and test) exactly
243 # which field names are accepted here. Are we case-sensitive?
244 # What do we do with fields that share names with Python keywords
245 # like 'lambda' and 'yield'?
246 #
247 # nnorwitz says:
248 # """
249 # Typically (in python), an underscore is appended to names that are
250 # keywords. So they would become lambda_ or yield_.
251 # """
252 def ListFields(self):
253 """Returns a list of (FieldDescriptor, value) tuples for present fields.
255 A message field is non-empty if HasField() would return true. A singular
256 primitive field is non-empty if HasField() would return true in proto2 or it
257 is non zero in proto3. A repeated field is non-empty if it contains at least
258 one element. The fields are ordered by field number.
260 Returns:
261 list[tuple(FieldDescriptor, value)]: field descriptors and values
262 for all fields in the message which are not empty. The values vary by
263 field type.
264 """
265 raise NotImplementedError
267 def HasField(self, field_name):
268 """Checks if a certain field is set for the message.
270 For a oneof group, checks if any field inside is set. Note that if the
271 field_name is not defined in the message descriptor, :exc:`ValueError` will
272 be raised.
274 Args:
275 field_name (str): The name of the field to check for presence.
277 Returns:
278 bool: Whether a value has been set for the named field.
280 Raises:
281 ValueError: if the `field_name` is not a member of this message.
282 """
283 raise NotImplementedError
285 def ClearField(self, field_name):
286 """Clears the contents of a given field.
288 Inside a oneof group, clears the field set. If the name neither refers to a
289 defined field or oneof group, :exc:`ValueError` is raised.
291 Args:
292 field_name (str): The name of the field to check for presence.
294 Raises:
295 ValueError: if the `field_name` is not a member of this message.
296 """
297 raise NotImplementedError
299 def WhichOneof(self, oneof_group):
300 """Returns the name of the field that is set inside a oneof group.
302 If no field is set, returns None.
304 Args:
305 oneof_group (str): the name of the oneof group to check.
307 Returns:
308 str or None: The name of the group that is set, or None.
310 Raises:
311 ValueError: no group with the given name exists
312 """
313 raise NotImplementedError
315 def HasExtension(self, field_descriptor):
316 """Checks if a certain extension is present for this message.
318 Extensions are retrieved using the :attr:`Extensions` mapping (if present).
320 Args:
321 field_descriptor: The field descriptor for the extension to check.
323 Returns:
324 bool: Whether the extension is present for this message.
326 Raises:
327 KeyError: if the extension is repeated. Similar to repeated fields,
328 there is no separate notion of presence: a "not present" repeated
329 extension is an empty list.
330 """
331 raise NotImplementedError
333 def ClearExtension(self, field_descriptor):
334 """Clears the contents of a given extension.
336 Args:
337 field_descriptor: The field descriptor for the extension to clear.
338 """
339 raise NotImplementedError
341 def UnknownFields(self):
342 """Returns the UnknownFieldSet.
344 Returns:
345 UnknownFieldSet: The unknown fields stored in this message.
346 """
347 raise NotImplementedError
349 def DiscardUnknownFields(self):
350 """Clears all fields in the :class:`UnknownFieldSet`.
352 This operation is recursive for nested message.
353 """
354 raise NotImplementedError
356 def ByteSize(self):
357 """Returns the serialized size of this message.
359 Recursively calls ByteSize() on all contained messages.
361 Returns:
362 int: The number of bytes required to serialize this message.
363 """
364 raise NotImplementedError
366 @classmethod
367 def FromString(cls, s):
368 raise NotImplementedError
370 @staticmethod
371 def RegisterExtension(field_descriptor):
372 raise NotImplementedError
374 def _SetListener(self, message_listener):
375 """Internal method used by the protocol message implementation.
376 Clients should not call this directly.
378 Sets a listener that this message will call on certain state transitions.
380 The purpose of this method is to register back-edges from children to
381 parents at runtime, for the purpose of setting "has" bits and
382 byte-size-dirty bits in the parent and ancestor objects whenever a child or
383 descendant object is modified.
385 If the client wants to disconnect this Message from the object tree, she
386 explicitly sets callback to None.
388 If message_listener is None, unregisters any existing listener. Otherwise,
389 message_listener must implement the MessageListener interface in
390 internal/message_listener.py, and we discard any listener registered
391 via a previous _SetListener() call.
392 """
393 raise NotImplementedError
395 def __getstate__(self):
396 """Support the pickle protocol."""
397 return dict(serialized=self.SerializePartialToString())
399 def __setstate__(self, state):
400 """Support the pickle protocol."""
401 self.__init__()
402 serialized = state['serialized']
403 # On Python 3, using encoding='latin1' is required for unpickling
404 # protos pickled by Python 2.
405 if not isinstance(serialized, bytes):
406 serialized = serialized.encode('latin1')
407 self.ParseFromString(serialized)
409 def __reduce__(self):
410 message_descriptor = self.DESCRIPTOR
411 if message_descriptor.containing_type is None:
412 return type(self), (), self.__getstate__()
413 # the message type must be nested.
414 # Python does not pickle nested classes; use the symbol_database on the
415 # receiving end.
416 container = message_descriptor
417 return (_InternalConstructMessage, (container.full_name,),
418 self.__getstate__())
421def _InternalConstructMessage(full_name):
422 """Constructs a nested message."""
423 from google.protobuf import symbol_database # pylint:disable=g-import-not-at-top
425 return symbol_database.Default().GetSymbol(full_name)()