message.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. #
  4. # Use of this source code is governed by a BSD-style
  5. # license that can be found in the LICENSE file or at
  6. # https://developers.google.com/open-source/licenses/bsd
  7. # TODO: We should just make these methods all "pure-virtual" and move
  8. # all implementation out, into reflection.py for now.
  9. """Contains an abstract base class for protocol messages."""
  10. __author__ = 'robinson@google.com (Will Robinson)'
  11. class Error(Exception):
  12. """Base error type for this module."""
  13. pass
  14. class DecodeError(Error):
  15. """Exception raised when deserializing messages."""
  16. pass
  17. class EncodeError(Error):
  18. """Exception raised when serializing messages."""
  19. pass
  20. class Message(object):
  21. """Abstract base class for protocol messages.
  22. Protocol message classes are almost always generated by the protocol
  23. compiler. These generated types subclass Message and implement the methods
  24. shown below.
  25. """
  26. # TODO: Link to an HTML document here.
  27. # TODO: Document that instances of this class will also
  28. # have an Extensions attribute with __getitem__ and __setitem__.
  29. # Again, not sure how to best convey this.
  30. # TODO: Document these fields and methods.
  31. __slots__ = []
  32. #: The :class:`google.protobuf.Descriptor`
  33. # for this message type.
  34. DESCRIPTOR = None
  35. def __deepcopy__(self, memo=None):
  36. clone = type(self)()
  37. clone.MergeFrom(self)
  38. return clone
  39. def __eq__(self, other_msg):
  40. """Recursively compares two messages by value and structure."""
  41. raise NotImplementedError
  42. def __ne__(self, other_msg):
  43. # Can't just say self != other_msg, since that would infinitely recurse. :)
  44. return not self == other_msg
  45. def __hash__(self):
  46. raise TypeError('unhashable object')
  47. def __str__(self):
  48. """Outputs a human-readable representation of the message."""
  49. raise NotImplementedError
  50. def __unicode__(self):
  51. """Outputs a human-readable representation of the message."""
  52. raise NotImplementedError
  53. def __contains__(self, field_name_or_key):
  54. """Checks if a certain field is set for the message.
  55. Has presence fields return true if the field is set, false if the field is
  56. not set. Fields without presence do raise `ValueError` (this includes
  57. repeated fields, map fields, and implicit presence fields).
  58. If field_name is not defined in the message descriptor, `ValueError` will
  59. be raised.
  60. Note: WKT Struct checks if the key is contained in fields. ListValue checks
  61. if the item is contained in the list.
  62. Args:
  63. field_name_or_key: For Struct, the key (str) of the fields map. For
  64. ListValue, any type that may be contained in the list. For other
  65. messages, name of the field (str) to check for presence.
  66. Returns:
  67. bool: For Struct, whether the item is contained in fields. For ListValue,
  68. whether the item is contained in the list. For other message,
  69. whether a value has been set for the named field.
  70. Raises:
  71. ValueError: For normal messages, if the `field_name_or_key` is not a
  72. member of this message or `field_name_or_key` is not a string.
  73. """
  74. raise NotImplementedError
  75. def MergeFrom(self, other_msg):
  76. """Merges the contents of the specified message into current message.
  77. This method merges the contents of the specified message into the current
  78. message. Singular fields that are set in the specified message overwrite
  79. the corresponding fields in the current message. Repeated fields are
  80. appended. Singular sub-messages and groups are recursively merged.
  81. Args:
  82. other_msg (Message): A message to merge into the current message.
  83. """
  84. raise NotImplementedError
  85. def CopyFrom(self, other_msg):
  86. """Copies the content of the specified message into the current message.
  87. The method clears the current message and then merges the specified
  88. message using MergeFrom.
  89. Args:
  90. other_msg (Message): A message to copy into the current one.
  91. """
  92. if self is other_msg:
  93. return
  94. self.Clear()
  95. self.MergeFrom(other_msg)
  96. def Clear(self):
  97. """Clears all data that was set in the message."""
  98. raise NotImplementedError
  99. def SetInParent(self):
  100. """Mark this as present in the parent.
  101. This normally happens automatically when you assign a field of a
  102. sub-message, but sometimes you want to make the sub-message
  103. present while keeping it empty. If you find yourself using this,
  104. you may want to reconsider your design.
  105. """
  106. raise NotImplementedError
  107. def IsInitialized(self):
  108. """Checks if the message is initialized.
  109. Returns:
  110. bool: The method returns True if the message is initialized (i.e. all of
  111. its required fields are set).
  112. """
  113. raise NotImplementedError
  114. # TODO: MergeFromString() should probably return None and be
  115. # implemented in terms of a helper that returns the # of bytes read. Our
  116. # deserialization routines would use the helper when recursively
  117. # deserializing, but the end user would almost always just want the no-return
  118. # MergeFromString().
  119. def MergeFromString(self, serialized):
  120. """Merges serialized protocol buffer data into this message.
  121. When we find a field in `serialized` that is already present
  122. in this message:
  123. - If it's a "repeated" field, we append to the end of our list.
  124. - Else, if it's a scalar, we overwrite our field.
  125. - Else, (it's a nonrepeated composite), we recursively merge
  126. into the existing composite.
  127. Args:
  128. serialized (bytes): Any object that allows us to call
  129. ``memoryview(serialized)`` to access a string of bytes using the
  130. buffer interface.
  131. Returns:
  132. int: The number of bytes read from `serialized`.
  133. For non-group messages, this will always be `len(serialized)`,
  134. but for messages which are actually groups, this will
  135. generally be less than `len(serialized)`, since we must
  136. stop when we reach an ``END_GROUP`` tag. Note that if
  137. we *do* stop because of an ``END_GROUP`` tag, the number
  138. of bytes returned does not include the bytes
  139. for the ``END_GROUP`` tag information.
  140. Raises:
  141. DecodeError: if the input cannot be parsed.
  142. """
  143. # TODO: Document handling of unknown fields.
  144. # TODO: When we switch to a helper, this will return None.
  145. raise NotImplementedError
  146. def ParseFromString(self, serialized):
  147. """Parse serialized protocol buffer data in binary form into this message.
  148. Like :func:`MergeFromString()`, except we clear the object first.
  149. Raises:
  150. message.DecodeError if the input cannot be parsed.
  151. """
  152. self.Clear()
  153. return self.MergeFromString(serialized)
  154. def SerializeToString(self, **kwargs):
  155. """Serializes the protocol message to a binary string.
  156. Keyword Args:
  157. deterministic (bool): If true, requests deterministic serialization
  158. of the protobuf, with predictable ordering of map keys.
  159. Returns:
  160. A binary string representation of the message if all of the required
  161. fields in the message are set (i.e. the message is initialized).
  162. Raises:
  163. EncodeError: if the message isn't initialized (see :func:`IsInitialized`).
  164. """
  165. raise NotImplementedError
  166. def SerializePartialToString(self, **kwargs):
  167. """Serializes the protocol message to a binary string.
  168. This method is similar to SerializeToString but doesn't check if the
  169. message is initialized.
  170. Keyword Args:
  171. deterministic (bool): If true, requests deterministic serialization
  172. of the protobuf, with predictable ordering of map keys.
  173. Returns:
  174. bytes: A serialized representation of the partial message.
  175. """
  176. raise NotImplementedError
  177. # TODO: Decide whether we like these better
  178. # than auto-generated has_foo() and clear_foo() methods
  179. # on the instances themselves. This way is less consistent
  180. # with C++, but it makes reflection-type access easier and
  181. # reduces the number of magically autogenerated things.
  182. #
  183. # TODO: Be sure to document (and test) exactly
  184. # which field names are accepted here. Are we case-sensitive?
  185. # What do we do with fields that share names with Python keywords
  186. # like 'lambda' and 'yield'?
  187. #
  188. # nnorwitz says:
  189. # """
  190. # Typically (in python), an underscore is appended to names that are
  191. # keywords. So they would become lambda_ or yield_.
  192. # """
  193. def ListFields(self):
  194. """Returns a list of (FieldDescriptor, value) tuples for present fields.
  195. A message field is non-empty if HasField() would return true. A singular
  196. primitive field is non-empty if HasField() would return true in proto2 or it
  197. is non zero in proto3. A repeated field is non-empty if it contains at least
  198. one element. The fields are ordered by field number.
  199. Returns:
  200. list[tuple(FieldDescriptor, value)]: field descriptors and values
  201. for all fields in the message which are not empty. The values vary by
  202. field type.
  203. """
  204. raise NotImplementedError
  205. def HasField(self, field_name):
  206. """Checks if a certain field is set for the message.
  207. For a oneof group, checks if any field inside is set. Note that if the
  208. field_name is not defined in the message descriptor, :exc:`ValueError` will
  209. be raised.
  210. Args:
  211. field_name (str): The name of the field to check for presence.
  212. Returns:
  213. bool: Whether a value has been set for the named field.
  214. Raises:
  215. ValueError: if the `field_name` is not a member of this message.
  216. """
  217. raise NotImplementedError
  218. def ClearField(self, field_name):
  219. """Clears the contents of a given field.
  220. Inside a oneof group, clears the field set. If the name neither refers to a
  221. defined field or oneof group, :exc:`ValueError` is raised.
  222. Args:
  223. field_name (str): The name of the field to check for presence.
  224. Raises:
  225. ValueError: if the `field_name` is not a member of this message.
  226. """
  227. raise NotImplementedError
  228. def WhichOneof(self, oneof_group):
  229. """Returns the name of the field that is set inside a oneof group.
  230. If no field is set, returns None.
  231. Args:
  232. oneof_group (str): the name of the oneof group to check.
  233. Returns:
  234. str or None: The name of the group that is set, or None.
  235. Raises:
  236. ValueError: no group with the given name exists
  237. """
  238. raise NotImplementedError
  239. def HasExtension(self, field_descriptor):
  240. """Checks if a certain extension is present for this message.
  241. Extensions are retrieved using the :attr:`Extensions` mapping (if present).
  242. Args:
  243. field_descriptor: The field descriptor for the extension to check.
  244. Returns:
  245. bool: Whether the extension is present for this message.
  246. Raises:
  247. KeyError: if the extension is repeated. Similar to repeated fields,
  248. there is no separate notion of presence: a "not present" repeated
  249. extension is an empty list.
  250. """
  251. raise NotImplementedError
  252. def ClearExtension(self, field_descriptor):
  253. """Clears the contents of a given extension.
  254. Args:
  255. field_descriptor: The field descriptor for the extension to clear.
  256. """
  257. raise NotImplementedError
  258. def UnknownFields(self):
  259. """Returns the UnknownFieldSet.
  260. Returns:
  261. UnknownFieldSet: The unknown fields stored in this message.
  262. """
  263. raise NotImplementedError
  264. def DiscardUnknownFields(self):
  265. """Clears all fields in the :class:`UnknownFieldSet`.
  266. This operation is recursive for nested message.
  267. """
  268. raise NotImplementedError
  269. def ByteSize(self):
  270. """Returns the serialized size of this message.
  271. Recursively calls ByteSize() on all contained messages.
  272. Returns:
  273. int: The number of bytes required to serialize this message.
  274. """
  275. raise NotImplementedError
  276. @classmethod
  277. def FromString(cls, s):
  278. raise NotImplementedError
  279. def _SetListener(self, message_listener):
  280. """Internal method used by the protocol message implementation.
  281. Clients should not call this directly.
  282. Sets a listener that this message will call on certain state transitions.
  283. The purpose of this method is to register back-edges from children to
  284. parents at runtime, for the purpose of setting "has" bits and
  285. byte-size-dirty bits in the parent and ancestor objects whenever a child or
  286. descendant object is modified.
  287. If the client wants to disconnect this Message from the object tree, she
  288. explicitly sets callback to None.
  289. If message_listener is None, unregisters any existing listener. Otherwise,
  290. message_listener must implement the MessageListener interface in
  291. internal/message_listener.py, and we discard any listener registered
  292. via a previous _SetListener() call.
  293. """
  294. raise NotImplementedError
  295. def __getstate__(self):
  296. """Support the pickle protocol."""
  297. return dict(serialized=self.SerializePartialToString())
  298. def __setstate__(self, state):
  299. """Support the pickle protocol."""
  300. self.__init__()
  301. serialized = state['serialized']
  302. # On Python 3, using encoding='latin1' is required for unpickling
  303. # protos pickled by Python 2.
  304. if not isinstance(serialized, bytes):
  305. serialized = serialized.encode('latin1')
  306. self.ParseFromString(serialized)
  307. def __reduce__(self):
  308. message_descriptor = self.DESCRIPTOR
  309. if message_descriptor.containing_type is None:
  310. return type(self), (), self.__getstate__()
  311. # the message type must be nested.
  312. # Python does not pickle nested classes; use the symbol_database on the
  313. # receiving end.
  314. container = message_descriptor
  315. return (_InternalConstructMessage, (container.full_name,),
  316. self.__getstate__())
  317. def _InternalConstructMessage(full_name):
  318. """Constructs a nested message."""
  319. from google.protobuf import symbol_database # pylint:disable=g-import-not-at-top
  320. return symbol_database.Default().GetSymbol(full_name)()