_collections_abc.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. # Copyright 2007 Google, Inc. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Abstract Base Classes (ABCs) for collections, according to PEP 3119.
  4. Unit tests are in test_collections.
  5. """
  6. from abc import ABCMeta, abstractmethod
  7. import sys
  8. __all__ = ["Awaitable", "Coroutine",
  9. "AsyncIterable", "AsyncIterator", "AsyncGenerator",
  10. "Hashable", "Iterable", "Iterator", "Generator", "Reversible",
  11. "Sized", "Container", "Callable", "Collection",
  12. "Set", "MutableSet",
  13. "Mapping", "MutableMapping",
  14. "MappingView", "KeysView", "ItemsView", "ValuesView",
  15. "Sequence", "MutableSequence",
  16. "ByteString",
  17. ]
  18. # This module has been renamed from collections.abc to _collections_abc to
  19. # speed up interpreter startup. Some of the types such as MutableMapping are
  20. # required early but collections module imports a lot of other modules.
  21. # See issue #19218
  22. __name__ = "collections.abc"
  23. # Private list of types that we want to register with the various ABCs
  24. # so that they will pass tests like:
  25. # it = iter(somebytearray)
  26. # assert isinstance(it, Iterable)
  27. # Note: in other implementations, these types might not be distinct
  28. # and they may have their own implementation specific types that
  29. # are not included on this list.
  30. bytes_iterator = type(iter(b''))
  31. bytearray_iterator = type(iter(bytearray()))
  32. #callable_iterator = ???
  33. dict_keyiterator = type(iter({}.keys()))
  34. dict_valueiterator = type(iter({}.values()))
  35. dict_itemiterator = type(iter({}.items()))
  36. list_iterator = type(iter([]))
  37. list_reverseiterator = type(iter(reversed([])))
  38. range_iterator = type(iter(range(0)))
  39. longrange_iterator = type(iter(range(1 << 1000)))
  40. set_iterator = type(iter(set()))
  41. str_iterator = type(iter(""))
  42. tuple_iterator = type(iter(()))
  43. zip_iterator = type(iter(zip()))
  44. ## views ##
  45. dict_keys = type({}.keys())
  46. dict_values = type({}.values())
  47. dict_items = type({}.items())
  48. ## misc ##
  49. mappingproxy = type(type.__dict__)
  50. generator = type((lambda: (yield))())
  51. ## coroutine ##
  52. async def _coro(): pass
  53. _coro = _coro()
  54. coroutine = type(_coro)
  55. _coro.close() # Prevent ResourceWarning
  56. del _coro
  57. ## asynchronous generator ##
  58. async def _ag(): yield
  59. _ag = _ag()
  60. async_generator = type(_ag)
  61. del _ag
  62. ### ONE-TRICK PONIES ###
  63. def _check_methods(C, *methods):
  64. mro = C.__mro__
  65. for method in methods:
  66. for B in mro:
  67. if method in B.__dict__:
  68. if B.__dict__[method] is None:
  69. return NotImplemented
  70. break
  71. else:
  72. return NotImplemented
  73. return True
  74. class Hashable(metaclass=ABCMeta):
  75. __slots__ = ()
  76. @abstractmethod
  77. def __hash__(self):
  78. return 0
  79. @classmethod
  80. def __subclasshook__(cls, C):
  81. if cls is Hashable:
  82. return _check_methods(C, "__hash__")
  83. return NotImplemented
  84. class Awaitable(metaclass=ABCMeta):
  85. __slots__ = ()
  86. @abstractmethod
  87. def __await__(self):
  88. yield
  89. @classmethod
  90. def __subclasshook__(cls, C):
  91. if cls is Awaitable:
  92. return _check_methods(C, "__await__")
  93. return NotImplemented
  94. class Coroutine(Awaitable):
  95. __slots__ = ()
  96. @abstractmethod
  97. def send(self, value):
  98. """Send a value into the coroutine.
  99. Return next yielded value or raise StopIteration.
  100. """
  101. raise StopIteration
  102. @abstractmethod
  103. def throw(self, typ, val=None, tb=None):
  104. """Raise an exception in the coroutine.
  105. Return next yielded value or raise StopIteration.
  106. """
  107. if val is None:
  108. if tb is None:
  109. raise typ
  110. val = typ()
  111. if tb is not None:
  112. val = val.with_traceback(tb)
  113. raise val
  114. def close(self):
  115. """Raise GeneratorExit inside coroutine.
  116. """
  117. try:
  118. self.throw(GeneratorExit)
  119. except (GeneratorExit, StopIteration):
  120. pass
  121. else:
  122. raise RuntimeError("coroutine ignored GeneratorExit")
  123. @classmethod
  124. def __subclasshook__(cls, C):
  125. if cls is Coroutine:
  126. return _check_methods(C, '__await__', 'send', 'throw', 'close')
  127. return NotImplemented
  128. Coroutine.register(coroutine)
  129. class AsyncIterable(metaclass=ABCMeta):
  130. __slots__ = ()
  131. @abstractmethod
  132. def __aiter__(self):
  133. return AsyncIterator()
  134. @classmethod
  135. def __subclasshook__(cls, C):
  136. if cls is AsyncIterable:
  137. return _check_methods(C, "__aiter__")
  138. return NotImplemented
  139. class AsyncIterator(AsyncIterable):
  140. __slots__ = ()
  141. @abstractmethod
  142. async def __anext__(self):
  143. """Return the next item or raise StopAsyncIteration when exhausted."""
  144. raise StopAsyncIteration
  145. def __aiter__(self):
  146. return self
  147. @classmethod
  148. def __subclasshook__(cls, C):
  149. if cls is AsyncIterator:
  150. return _check_methods(C, "__anext__", "__aiter__")
  151. return NotImplemented
  152. class AsyncGenerator(AsyncIterator):
  153. __slots__ = ()
  154. async def __anext__(self):
  155. """Return the next item from the asynchronous generator.
  156. When exhausted, raise StopAsyncIteration.
  157. """
  158. return await self.asend(None)
  159. @abstractmethod
  160. async def asend(self, value):
  161. """Send a value into the asynchronous generator.
  162. Return next yielded value or raise StopAsyncIteration.
  163. """
  164. raise StopAsyncIteration
  165. @abstractmethod
  166. async def athrow(self, typ, val=None, tb=None):
  167. """Raise an exception in the asynchronous generator.
  168. Return next yielded value or raise StopAsyncIteration.
  169. """
  170. if val is None:
  171. if tb is None:
  172. raise typ
  173. val = typ()
  174. if tb is not None:
  175. val = val.with_traceback(tb)
  176. raise val
  177. async def aclose(self):
  178. """Raise GeneratorExit inside coroutine.
  179. """
  180. try:
  181. await self.athrow(GeneratorExit)
  182. except (GeneratorExit, StopAsyncIteration):
  183. pass
  184. else:
  185. raise RuntimeError("asynchronous generator ignored GeneratorExit")
  186. @classmethod
  187. def __subclasshook__(cls, C):
  188. if cls is AsyncGenerator:
  189. return _check_methods(C, '__aiter__', '__anext__',
  190. 'asend', 'athrow', 'aclose')
  191. return NotImplemented
  192. AsyncGenerator.register(async_generator)
  193. class Iterable(metaclass=ABCMeta):
  194. __slots__ = ()
  195. @abstractmethod
  196. def __iter__(self):
  197. while False:
  198. yield None
  199. @classmethod
  200. def __subclasshook__(cls, C):
  201. if cls is Iterable:
  202. return _check_methods(C, "__iter__")
  203. return NotImplemented
  204. class Iterator(Iterable):
  205. __slots__ = ()
  206. @abstractmethod
  207. def __next__(self):
  208. 'Return the next item from the iterator. When exhausted, raise StopIteration'
  209. raise StopIteration
  210. def __iter__(self):
  211. return self
  212. @classmethod
  213. def __subclasshook__(cls, C):
  214. if cls is Iterator:
  215. return _check_methods(C, '__iter__', '__next__')
  216. return NotImplemented
  217. Iterator.register(bytes_iterator)
  218. Iterator.register(bytearray_iterator)
  219. #Iterator.register(callable_iterator)
  220. Iterator.register(dict_keyiterator)
  221. Iterator.register(dict_valueiterator)
  222. Iterator.register(dict_itemiterator)
  223. Iterator.register(list_iterator)
  224. Iterator.register(list_reverseiterator)
  225. Iterator.register(range_iterator)
  226. Iterator.register(longrange_iterator)
  227. Iterator.register(set_iterator)
  228. Iterator.register(str_iterator)
  229. Iterator.register(tuple_iterator)
  230. Iterator.register(zip_iterator)
  231. class Reversible(Iterable):
  232. __slots__ = ()
  233. @abstractmethod
  234. def __reversed__(self):
  235. while False:
  236. yield None
  237. @classmethod
  238. def __subclasshook__(cls, C):
  239. if cls is Reversible:
  240. return _check_methods(C, "__reversed__", "__iter__")
  241. return NotImplemented
  242. class Generator(Iterator):
  243. __slots__ = ()
  244. def __next__(self):
  245. """Return the next item from the generator.
  246. When exhausted, raise StopIteration.
  247. """
  248. return self.send(None)
  249. @abstractmethod
  250. def send(self, value):
  251. """Send a value into the generator.
  252. Return next yielded value or raise StopIteration.
  253. """
  254. raise StopIteration
  255. @abstractmethod
  256. def throw(self, typ, val=None, tb=None):
  257. """Raise an exception in the generator.
  258. Return next yielded value or raise StopIteration.
  259. """
  260. if val is None:
  261. if tb is None:
  262. raise typ
  263. val = typ()
  264. if tb is not None:
  265. val = val.with_traceback(tb)
  266. raise val
  267. def close(self):
  268. """Raise GeneratorExit inside generator.
  269. """
  270. try:
  271. self.throw(GeneratorExit)
  272. except (GeneratorExit, StopIteration):
  273. pass
  274. else:
  275. raise RuntimeError("generator ignored GeneratorExit")
  276. @classmethod
  277. def __subclasshook__(cls, C):
  278. if cls is Generator:
  279. return _check_methods(C, '__iter__', '__next__',
  280. 'send', 'throw', 'close')
  281. return NotImplemented
  282. Generator.register(generator)
  283. class Sized(metaclass=ABCMeta):
  284. __slots__ = ()
  285. @abstractmethod
  286. def __len__(self):
  287. return 0
  288. @classmethod
  289. def __subclasshook__(cls, C):
  290. if cls is Sized:
  291. return _check_methods(C, "__len__")
  292. return NotImplemented
  293. class Container(metaclass=ABCMeta):
  294. __slots__ = ()
  295. @abstractmethod
  296. def __contains__(self, x):
  297. return False
  298. @classmethod
  299. def __subclasshook__(cls, C):
  300. if cls is Container:
  301. return _check_methods(C, "__contains__")
  302. return NotImplemented
  303. class Collection(Sized, Iterable, Container):
  304. __slots__ = ()
  305. @classmethod
  306. def __subclasshook__(cls, C):
  307. if cls is Collection:
  308. return _check_methods(C, "__len__", "__iter__", "__contains__")
  309. return NotImplemented
  310. class Callable(metaclass=ABCMeta):
  311. __slots__ = ()
  312. @abstractmethod
  313. def __call__(self, *args, **kwds):
  314. return False
  315. @classmethod
  316. def __subclasshook__(cls, C):
  317. if cls is Callable:
  318. return _check_methods(C, "__call__")
  319. return NotImplemented
  320. ### SETS ###
  321. class Set(Collection):
  322. """A set is a finite, iterable container.
  323. This class provides concrete generic implementations of all
  324. methods except for __contains__, __iter__ and __len__.
  325. To override the comparisons (presumably for speed, as the
  326. semantics are fixed), redefine __le__ and __ge__,
  327. then the other operations will automatically follow suit.
  328. """
  329. __slots__ = ()
  330. def __le__(self, other):
  331. if not isinstance(other, Set):
  332. return NotImplemented
  333. if len(self) > len(other):
  334. return False
  335. for elem in self:
  336. if elem not in other:
  337. return False
  338. return True
  339. def __lt__(self, other):
  340. if not isinstance(other, Set):
  341. return NotImplemented
  342. return len(self) < len(other) and self.__le__(other)
  343. def __gt__(self, other):
  344. if not isinstance(other, Set):
  345. return NotImplemented
  346. return len(self) > len(other) and self.__ge__(other)
  347. def __ge__(self, other):
  348. if not isinstance(other, Set):
  349. return NotImplemented
  350. if len(self) < len(other):
  351. return False
  352. for elem in other:
  353. if elem not in self:
  354. return False
  355. return True
  356. def __eq__(self, other):
  357. if not isinstance(other, Set):
  358. return NotImplemented
  359. return len(self) == len(other) and self.__le__(other)
  360. @classmethod
  361. def _from_iterable(cls, it):
  362. '''Construct an instance of the class from any iterable input.
  363. Must override this method if the class constructor signature
  364. does not accept an iterable for an input.
  365. '''
  366. return cls(it)
  367. def __and__(self, other):
  368. if not isinstance(other, Iterable):
  369. return NotImplemented
  370. return self._from_iterable(value for value in other if value in self)
  371. __rand__ = __and__
  372. def isdisjoint(self, other):
  373. 'Return True if two sets have a null intersection.'
  374. for value in other:
  375. if value in self:
  376. return False
  377. return True
  378. def __or__(self, other):
  379. if not isinstance(other, Iterable):
  380. return NotImplemented
  381. chain = (e for s in (self, other) for e in s)
  382. return self._from_iterable(chain)
  383. __ror__ = __or__
  384. def __sub__(self, other):
  385. if not isinstance(other, Set):
  386. if not isinstance(other, Iterable):
  387. return NotImplemented
  388. other = self._from_iterable(other)
  389. return self._from_iterable(value for value in self
  390. if value not in other)
  391. def __rsub__(self, other):
  392. if not isinstance(other, Set):
  393. if not isinstance(other, Iterable):
  394. return NotImplemented
  395. other = self._from_iterable(other)
  396. return self._from_iterable(value for value in other
  397. if value not in self)
  398. def __xor__(self, other):
  399. if not isinstance(other, Set):
  400. if not isinstance(other, Iterable):
  401. return NotImplemented
  402. other = self._from_iterable(other)
  403. return (self - other) | (other - self)
  404. __rxor__ = __xor__
  405. def _hash(self):
  406. """Compute the hash value of a set.
  407. Note that we don't define __hash__: not all sets are hashable.
  408. But if you define a hashable set type, its __hash__ should
  409. call this function.
  410. This must be compatible __eq__.
  411. All sets ought to compare equal if they contain the same
  412. elements, regardless of how they are implemented, and
  413. regardless of the order of the elements; so there's not much
  414. freedom for __eq__ or __hash__. We match the algorithm used
  415. by the built-in frozenset type.
  416. """
  417. MAX = sys.maxsize
  418. MASK = 2 * MAX + 1
  419. n = len(self)
  420. h = 1927868237 * (n + 1)
  421. h &= MASK
  422. for x in self:
  423. hx = hash(x)
  424. h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
  425. h &= MASK
  426. h = h * 69069 + 907133923
  427. h &= MASK
  428. if h > MAX:
  429. h -= MASK + 1
  430. if h == -1:
  431. h = 590923713
  432. return h
  433. Set.register(frozenset)
  434. class MutableSet(Set):
  435. """A mutable set is a finite, iterable container.
  436. This class provides concrete generic implementations of all
  437. methods except for __contains__, __iter__, __len__,
  438. add(), and discard().
  439. To override the comparisons (presumably for speed, as the
  440. semantics are fixed), all you have to do is redefine __le__ and
  441. then the other operations will automatically follow suit.
  442. """
  443. __slots__ = ()
  444. @abstractmethod
  445. def add(self, value):
  446. """Add an element."""
  447. raise NotImplementedError
  448. @abstractmethod
  449. def discard(self, value):
  450. """Remove an element. Do not raise an exception if absent."""
  451. raise NotImplementedError
  452. def remove(self, value):
  453. """Remove an element. If not a member, raise a KeyError."""
  454. if value not in self:
  455. raise KeyError(value)
  456. self.discard(value)
  457. def pop(self):
  458. """Return the popped value. Raise KeyError if empty."""
  459. it = iter(self)
  460. try:
  461. value = next(it)
  462. except StopIteration:
  463. raise KeyError from None
  464. self.discard(value)
  465. return value
  466. def clear(self):
  467. """This is slow (creates N new iterators!) but effective."""
  468. try:
  469. while True:
  470. self.pop()
  471. except KeyError:
  472. pass
  473. def __ior__(self, it):
  474. for value in it:
  475. self.add(value)
  476. return self
  477. def __iand__(self, it):
  478. for value in (self - it):
  479. self.discard(value)
  480. return self
  481. def __ixor__(self, it):
  482. if it is self:
  483. self.clear()
  484. else:
  485. if not isinstance(it, Set):
  486. it = self._from_iterable(it)
  487. for value in it:
  488. if value in self:
  489. self.discard(value)
  490. else:
  491. self.add(value)
  492. return self
  493. def __isub__(self, it):
  494. if it is self:
  495. self.clear()
  496. else:
  497. for value in it:
  498. self.discard(value)
  499. return self
  500. MutableSet.register(set)
  501. ### MAPPINGS ###
  502. class Mapping(Collection):
  503. __slots__ = ()
  504. """A Mapping is a generic container for associating key/value
  505. pairs.
  506. This class provides concrete generic implementations of all
  507. methods except for __getitem__, __iter__, and __len__.
  508. """
  509. @abstractmethod
  510. def __getitem__(self, key):
  511. raise KeyError
  512. def get(self, key, default=None):
  513. 'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
  514. try:
  515. return self[key]
  516. except KeyError:
  517. return default
  518. def __contains__(self, key):
  519. try:
  520. self[key]
  521. except KeyError:
  522. return False
  523. else:
  524. return True
  525. def keys(self):
  526. "D.keys() -> a set-like object providing a view on D's keys"
  527. return KeysView(self)
  528. def items(self):
  529. "D.items() -> a set-like object providing a view on D's items"
  530. return ItemsView(self)
  531. def values(self):
  532. "D.values() -> an object providing a view on D's values"
  533. return ValuesView(self)
  534. def __eq__(self, other):
  535. if not isinstance(other, Mapping):
  536. return NotImplemented
  537. return dict(self.items()) == dict(other.items())
  538. __reversed__ = None
  539. Mapping.register(mappingproxy)
  540. class MappingView(Sized):
  541. __slots__ = '_mapping',
  542. def __init__(self, mapping):
  543. self._mapping = mapping
  544. def __len__(self):
  545. return len(self._mapping)
  546. def __repr__(self):
  547. return '{0.__class__.__name__}({0._mapping!r})'.format(self)
  548. class KeysView(MappingView, Set):
  549. __slots__ = ()
  550. @classmethod
  551. def _from_iterable(self, it):
  552. return set(it)
  553. def __contains__(self, key):
  554. return key in self._mapping
  555. def __iter__(self):
  556. yield from self._mapping
  557. KeysView.register(dict_keys)
  558. class ItemsView(MappingView, Set):
  559. __slots__ = ()
  560. @classmethod
  561. def _from_iterable(self, it):
  562. return set(it)
  563. def __contains__(self, item):
  564. key, value = item
  565. try:
  566. v = self._mapping[key]
  567. except KeyError:
  568. return False
  569. else:
  570. return v is value or v == value
  571. def __iter__(self):
  572. for key in self._mapping:
  573. yield (key, self._mapping[key])
  574. ItemsView.register(dict_items)
  575. class ValuesView(MappingView, Collection):
  576. __slots__ = ()
  577. def __contains__(self, value):
  578. for key in self._mapping:
  579. v = self._mapping[key]
  580. if v is value or v == value:
  581. return True
  582. return False
  583. def __iter__(self):
  584. for key in self._mapping:
  585. yield self._mapping[key]
  586. ValuesView.register(dict_values)
  587. class MutableMapping(Mapping):
  588. __slots__ = ()
  589. """A MutableMapping is a generic container for associating
  590. key/value pairs.
  591. This class provides concrete generic implementations of all
  592. methods except for __getitem__, __setitem__, __delitem__,
  593. __iter__, and __len__.
  594. """
  595. @abstractmethod
  596. def __setitem__(self, key, value):
  597. raise KeyError
  598. @abstractmethod
  599. def __delitem__(self, key):
  600. raise KeyError
  601. __marker = object()
  602. def pop(self, key, default=__marker):
  603. '''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  604. If key is not found, d is returned if given, otherwise KeyError is raised.
  605. '''
  606. try:
  607. value = self[key]
  608. except KeyError:
  609. if default is self.__marker:
  610. raise
  611. return default
  612. else:
  613. del self[key]
  614. return value
  615. def popitem(self):
  616. '''D.popitem() -> (k, v), remove and return some (key, value) pair
  617. as a 2-tuple; but raise KeyError if D is empty.
  618. '''
  619. try:
  620. key = next(iter(self))
  621. except StopIteration:
  622. raise KeyError from None
  623. value = self[key]
  624. del self[key]
  625. return key, value
  626. def clear(self):
  627. 'D.clear() -> None. Remove all items from D.'
  628. try:
  629. while True:
  630. self.popitem()
  631. except KeyError:
  632. pass
  633. def update(*args, **kwds):
  634. ''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
  635. If E present and has a .keys() method, does: for k in E: D[k] = E[k]
  636. If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
  637. In either case, this is followed by: for k, v in F.items(): D[k] = v
  638. '''
  639. if not args:
  640. raise TypeError("descriptor 'update' of 'MutableMapping' object "
  641. "needs an argument")
  642. self, *args = args
  643. if len(args) > 1:
  644. raise TypeError('update expected at most 1 arguments, got %d' %
  645. len(args))
  646. if args:
  647. other = args[0]
  648. if isinstance(other, Mapping):
  649. for key in other:
  650. self[key] = other[key]
  651. elif hasattr(other, "keys"):
  652. for key in other.keys():
  653. self[key] = other[key]
  654. else:
  655. for key, value in other:
  656. self[key] = value
  657. for key, value in kwds.items():
  658. self[key] = value
  659. def setdefault(self, key, default=None):
  660. 'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D'
  661. try:
  662. return self[key]
  663. except KeyError:
  664. self[key] = default
  665. return default
  666. MutableMapping.register(dict)
  667. ### SEQUENCES ###
  668. class Sequence(Reversible, Collection):
  669. """All the operations on a read-only sequence.
  670. Concrete subclasses must override __new__ or __init__,
  671. __getitem__, and __len__.
  672. """
  673. __slots__ = ()
  674. @abstractmethod
  675. def __getitem__(self, index):
  676. raise IndexError
  677. def __iter__(self):
  678. i = 0
  679. try:
  680. while True:
  681. v = self[i]
  682. yield v
  683. i += 1
  684. except IndexError:
  685. return
  686. def __contains__(self, value):
  687. for v in self:
  688. if v is value or v == value:
  689. return True
  690. return False
  691. def __reversed__(self):
  692. for i in reversed(range(len(self))):
  693. yield self[i]
  694. def index(self, value, start=0, stop=None):
  695. '''S.index(value, [start, [stop]]) -> integer -- return first index of value.
  696. Raises ValueError if the value is not present.
  697. Supporting start and stop arguments is optional, but
  698. recommended.
  699. '''
  700. if start is not None and start < 0:
  701. start = max(len(self) + start, 0)
  702. if stop is not None and stop < 0:
  703. stop += len(self)
  704. i = start
  705. while stop is None or i < stop:
  706. try:
  707. v = self[i]
  708. if v is value or v == value:
  709. return i
  710. except IndexError:
  711. break
  712. i += 1
  713. raise ValueError
  714. def count(self, value):
  715. 'S.count(value) -> integer -- return number of occurrences of value'
  716. return sum(1 for v in self if v is value or v == value)
  717. Sequence.register(tuple)
  718. Sequence.register(str)
  719. Sequence.register(range)
  720. Sequence.register(memoryview)
  721. class ByteString(Sequence):
  722. """This unifies bytes and bytearray.
  723. XXX Should add all their methods.
  724. """
  725. __slots__ = ()
  726. ByteString.register(bytes)
  727. ByteString.register(bytearray)
  728. class MutableSequence(Sequence):
  729. __slots__ = ()
  730. """All the operations on a read-write sequence.
  731. Concrete subclasses must provide __new__ or __init__,
  732. __getitem__, __setitem__, __delitem__, __len__, and insert().
  733. """
  734. @abstractmethod
  735. def __setitem__(self, index, value):
  736. raise IndexError
  737. @abstractmethod
  738. def __delitem__(self, index):
  739. raise IndexError
  740. @abstractmethod
  741. def insert(self, index, value):
  742. 'S.insert(index, value) -- insert value before index'
  743. raise IndexError
  744. def append(self, value):
  745. 'S.append(value) -- append value to the end of the sequence'
  746. self.insert(len(self), value)
  747. def clear(self):
  748. 'S.clear() -> None -- remove all items from S'
  749. try:
  750. while True:
  751. self.pop()
  752. except IndexError:
  753. pass
  754. def reverse(self):
  755. 'S.reverse() -- reverse *IN PLACE*'
  756. n = len(self)
  757. for i in range(n//2):
  758. self[i], self[n-i-1] = self[n-i-1], self[i]
  759. def extend(self, values):
  760. 'S.extend(iterable) -- extend sequence by appending elements from the iterable'
  761. for v in values:
  762. self.append(v)
  763. def pop(self, index=-1):
  764. '''S.pop([index]) -> item -- remove and return item at index (default last).
  765. Raise IndexError if list is empty or index is out of range.
  766. '''
  767. v = self[index]
  768. del self[index]
  769. return v
  770. def remove(self, value):
  771. '''S.remove(value) -- remove first occurrence of value.
  772. Raise ValueError if the value is not present.
  773. '''
  774. del self[self.index(value)]
  775. def __iadd__(self, values):
  776. self.extend(values)
  777. return self
  778. MutableSequence.register(list)
  779. MutableSequence.register(bytearray) # Multiply inheriting, see ByteString