Package google :: Package protobuf :: Module message
[hide private]
[frames] | no frames]

Source Code for Module google.protobuf.message

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