店播爬取Python脚本

containers.py 25KB

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