Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

_collections_abc.py 26 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
  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
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...