Guido van Rossum | 64c06e3 | 2007-11-22 00:55:51 +0000 | [diff] [blame] | 1 | # Copyright 2007 Google, Inc. All Rights Reserved. |
| 2 | # Licensed to PSF under a Contributor Agreement. |
| 3 | |
| 4 | """Abstract Base Classes (ABCs) for collections, according to PEP 3119. |
| 5 | |
| 6 | DON'T USE THIS MODULE DIRECTLY! The classes here should be imported |
| 7 | via collections; they are defined here only to alleviate certain |
| 8 | bootstrapping issues. Unit tests are in test_collections. |
| 9 | """ |
| 10 | |
| 11 | from abc import ABCMeta, abstractmethod |
| 12 | |
| 13 | __all__ = ["Hashable", "Iterable", "Iterator", |
| 14 | "Sized", "Container", "Callable", |
| 15 | "Set", "MutableSet", |
| 16 | "Mapping", "MutableMapping", |
| 17 | "MappingView", "KeysView", "ItemsView", "ValuesView", |
| 18 | "Sequence", "MutableSequence", |
| 19 | ] |
| 20 | |
| 21 | ### ONE-TRICK PONIES ### |
| 22 | |
| 23 | class Hashable: |
| 24 | __metaclass__ = ABCMeta |
| 25 | |
| 26 | @abstractmethod |
| 27 | def __hash__(self): |
| 28 | return 0 |
| 29 | |
| 30 | @classmethod |
| 31 | def __subclasshook__(cls, C): |
| 32 | if cls is Hashable: |
| 33 | for B in C.__mro__: |
| 34 | if "__hash__" in B.__dict__: |
| 35 | if B.__dict__["__hash__"]: |
| 36 | return True |
| 37 | break |
| 38 | return NotImplemented |
| 39 | |
| 40 | |
| 41 | class Iterable: |
| 42 | __metaclass__ = ABCMeta |
| 43 | |
| 44 | @abstractmethod |
| 45 | def __iter__(self): |
| 46 | while False: |
| 47 | yield None |
| 48 | |
| 49 | @classmethod |
| 50 | def __subclasshook__(cls, C): |
| 51 | if cls is Iterable: |
| 52 | if any("__iter__" in B.__dict__ for B in C.__mro__): |
| 53 | return True |
| 54 | return NotImplemented |
| 55 | |
| 56 | Iterable.register(str) |
| 57 | |
| 58 | |
| 59 | class Iterator: |
| 60 | __metaclass__ = ABCMeta |
| 61 | |
| 62 | @abstractmethod |
| 63 | def __next__(self): |
| 64 | raise StopIteration |
| 65 | |
| 66 | def __iter__(self): |
| 67 | return self |
| 68 | |
| 69 | @classmethod |
| 70 | def __subclasshook__(cls, C): |
| 71 | if cls is Iterator: |
| 72 | if any("next" in B.__dict__ for B in C.__mro__): |
| 73 | return True |
| 74 | return NotImplemented |
| 75 | |
| 76 | |
| 77 | class Sized: |
| 78 | __metaclass__ = ABCMeta |
| 79 | |
| 80 | @abstractmethod |
| 81 | def __len__(self): |
| 82 | return 0 |
| 83 | |
| 84 | @classmethod |
| 85 | def __subclasshook__(cls, C): |
| 86 | if cls is Sized: |
| 87 | if any("__len__" in B.__dict__ for B in C.__mro__): |
| 88 | return True |
| 89 | return NotImplemented |
| 90 | |
| 91 | |
| 92 | class Container: |
| 93 | __metaclass__ = ABCMeta |
| 94 | |
| 95 | @abstractmethod |
| 96 | def __contains__(self, x): |
| 97 | return False |
| 98 | |
| 99 | @classmethod |
| 100 | def __subclasshook__(cls, C): |
| 101 | if cls is Container: |
| 102 | if any("__contains__" in B.__dict__ for B in C.__mro__): |
| 103 | return True |
| 104 | return NotImplemented |
| 105 | |
| 106 | |
| 107 | class Callable: |
| 108 | __metaclass__ = ABCMeta |
| 109 | |
| 110 | @abstractmethod |
| 111 | def __contains__(self, x): |
| 112 | return False |
| 113 | |
| 114 | @classmethod |
| 115 | def __subclasshook__(cls, C): |
| 116 | if cls is Callable: |
| 117 | if any("__call__" in B.__dict__ for B in C.__mro__): |
| 118 | return True |
| 119 | return NotImplemented |
| 120 | |
| 121 | |
| 122 | ### SETS ### |
| 123 | |
| 124 | |
| 125 | class Set: |
| 126 | __metaclass__ = ABCMeta |
| 127 | |
| 128 | """A set is a finite, iterable container. |
| 129 | |
| 130 | This class provides concrete generic implementations of all |
| 131 | methods except for __contains__, __iter__ and __len__. |
| 132 | |
| 133 | To override the comparisons (presumably for speed, as the |
| 134 | semantics are fixed), all you have to do is redefine __le__ and |
| 135 | then the other operations will automatically follow suit. |
| 136 | """ |
| 137 | |
| 138 | @abstractmethod |
| 139 | def __contains__(self, value): |
| 140 | return False |
| 141 | |
| 142 | @abstractmethod |
| 143 | def __iter__(self): |
| 144 | while False: |
| 145 | yield None |
| 146 | |
| 147 | @abstractmethod |
| 148 | def __len__(self): |
| 149 | return 0 |
| 150 | |
| 151 | def __le__(self, other): |
| 152 | if not isinstance(other, Set): |
| 153 | return NotImplemented |
| 154 | if len(self) > len(other): |
| 155 | return False |
| 156 | for elem in self: |
| 157 | if elem not in other: |
| 158 | return False |
| 159 | return True |
| 160 | |
| 161 | def __lt__(self, other): |
| 162 | if not isinstance(other, Set): |
| 163 | return NotImplemented |
| 164 | return len(self) < len(other) and self.__le__(other) |
| 165 | |
| 166 | def __eq__(self, other): |
| 167 | if not isinstance(other, Set): |
| 168 | return NotImplemented |
| 169 | return len(self) == len(other) and self.__le__(other) |
| 170 | |
| 171 | @classmethod |
| 172 | def _from_iterable(cls, it): |
| 173 | return frozenset(it) |
| 174 | |
| 175 | def __and__(self, other): |
| 176 | if not isinstance(other, Iterable): |
| 177 | return NotImplemented |
| 178 | return self._from_iterable(value for value in other if value in self) |
| 179 | |
Raymond Hettinger | abf3fcf | 2008-01-30 00:01:07 +0000 | [diff] [blame] | 180 | def isdisjoint(self, other): |
| 181 | for value in other: |
| 182 | if value in self: |
| 183 | return False |
| 184 | return True |
| 185 | |
Guido van Rossum | 64c06e3 | 2007-11-22 00:55:51 +0000 | [diff] [blame] | 186 | def __or__(self, other): |
| 187 | if not isinstance(other, Iterable): |
| 188 | return NotImplemented |
| 189 | return self._from_iterable(itertools.chain(self, other)) |
| 190 | |
| 191 | def __sub__(self, other): |
| 192 | if not isinstance(other, Set): |
| 193 | if not isinstance(other, Iterable): |
| 194 | return NotImplemented |
| 195 | other = self._from_iterable(other) |
| 196 | return self._from_iterable(value for value in self |
| 197 | if value not in other) |
| 198 | |
| 199 | def __xor__(self, other): |
| 200 | if not isinstance(other, Set): |
| 201 | if not isinstance(other, Iterable): |
| 202 | return NotImplemented |
| 203 | other = self._from_iterable(other) |
| 204 | return (self - other) | (other - self) |
| 205 | |
| 206 | def _hash(self): |
| 207 | """Compute the hash value of a set. |
| 208 | |
| 209 | Note that we don't define __hash__: not all sets are hashable. |
| 210 | But if you define a hashable set type, its __hash__ should |
| 211 | call this function. |
| 212 | |
| 213 | This must be compatible __eq__. |
| 214 | |
| 215 | All sets ought to compare equal if they contain the same |
| 216 | elements, regardless of how they are implemented, and |
| 217 | regardless of the order of the elements; so there's not much |
| 218 | freedom for __eq__ or __hash__. We match the algorithm used |
| 219 | by the built-in frozenset type. |
| 220 | """ |
| 221 | MAX = sys.maxint |
| 222 | MASK = 2 * MAX + 1 |
| 223 | n = len(self) |
| 224 | h = 1927868237 * (n + 1) |
| 225 | h &= MASK |
| 226 | for x in self: |
| 227 | hx = hash(x) |
| 228 | h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167 |
| 229 | h &= MASK |
| 230 | h = h * 69069 + 907133923 |
| 231 | h &= MASK |
| 232 | if h > MAX: |
| 233 | h -= MASK + 1 |
| 234 | if h == -1: |
| 235 | h = 590923713 |
| 236 | return h |
| 237 | |
| 238 | Set.register(frozenset) |
| 239 | |
| 240 | |
| 241 | class MutableSet(Set): |
| 242 | |
| 243 | @abstractmethod |
| 244 | def add(self, value): |
| 245 | """Return True if it was added, False if already there.""" |
| 246 | raise NotImplementedError |
| 247 | |
| 248 | @abstractmethod |
| 249 | def discard(self, value): |
| 250 | """Return True if it was deleted, False if not there.""" |
| 251 | raise NotImplementedError |
| 252 | |
Raymond Hettinger | 7d518f4 | 2008-01-30 00:08:31 +0000 | [diff] [blame] | 253 | def remove(self, value): |
| 254 | """Remove an element. If not a member, raise a KeyError.""" |
| 255 | if value not in self: |
| 256 | raise KeyError(value) |
| 257 | self.discard(value) |
| 258 | |
Guido van Rossum | 64c06e3 | 2007-11-22 00:55:51 +0000 | [diff] [blame] | 259 | def pop(self): |
| 260 | """Return the popped value. Raise KeyError if empty.""" |
| 261 | it = iter(self) |
| 262 | try: |
| 263 | value = it.__next__() |
| 264 | except StopIteration: |
| 265 | raise KeyError |
| 266 | self.discard(value) |
| 267 | return value |
| 268 | |
| 269 | def toggle(self, value): |
| 270 | """Return True if it was added, False if deleted.""" |
| 271 | # XXX This implementation is not thread-safe |
| 272 | if value in self: |
| 273 | self.discard(value) |
| 274 | return False |
| 275 | else: |
| 276 | self.add(value) |
| 277 | return True |
| 278 | |
| 279 | def clear(self): |
| 280 | """This is slow (creates N new iterators!) but effective.""" |
| 281 | try: |
| 282 | while True: |
| 283 | self.pop() |
| 284 | except KeyError: |
| 285 | pass |
| 286 | |
| 287 | def __ior__(self, it): |
| 288 | for value in it: |
| 289 | self.add(value) |
| 290 | return self |
| 291 | |
| 292 | def __iand__(self, c): |
| 293 | for value in self: |
| 294 | if value not in c: |
| 295 | self.discard(value) |
| 296 | return self |
| 297 | |
| 298 | def __ixor__(self, it): |
| 299 | # This calls toggle(), so if that is overridded, we call the override |
| 300 | for value in it: |
| 301 | self.toggle(it) |
| 302 | return self |
| 303 | |
| 304 | def __isub__(self, it): |
| 305 | for value in it: |
| 306 | self.discard(value) |
| 307 | return self |
| 308 | |
| 309 | MutableSet.register(set) |
| 310 | |
| 311 | |
| 312 | ### MAPPINGS ### |
| 313 | |
| 314 | |
| 315 | class Mapping: |
| 316 | __metaclass__ = ABCMeta |
| 317 | |
| 318 | @abstractmethod |
| 319 | def __getitem__(self, key): |
| 320 | raise KeyError |
| 321 | |
| 322 | def get(self, key, default=None): |
| 323 | try: |
| 324 | return self[key] |
| 325 | except KeyError: |
| 326 | return default |
| 327 | |
| 328 | def __contains__(self, key): |
| 329 | try: |
| 330 | self[key] |
| 331 | except KeyError: |
| 332 | return False |
| 333 | else: |
| 334 | return True |
| 335 | |
| 336 | @abstractmethod |
| 337 | def __len__(self): |
| 338 | return 0 |
| 339 | |
| 340 | @abstractmethod |
| 341 | def __iter__(self): |
| 342 | while False: |
| 343 | yield None |
| 344 | |
| 345 | def keys(self): |
| 346 | return KeysView(self) |
| 347 | |
| 348 | def items(self): |
| 349 | return ItemsView(self) |
| 350 | |
| 351 | def values(self): |
| 352 | return ValuesView(self) |
| 353 | |
| 354 | |
| 355 | class MappingView: |
| 356 | __metaclass__ = ABCMeta |
| 357 | |
| 358 | def __init__(self, mapping): |
| 359 | self._mapping = mapping |
| 360 | |
| 361 | def __len__(self): |
| 362 | return len(self._mapping) |
| 363 | |
| 364 | |
| 365 | class KeysView(MappingView, Set): |
| 366 | |
| 367 | def __contains__(self, key): |
| 368 | return key in self._mapping |
| 369 | |
| 370 | def __iter__(self): |
| 371 | for key in self._mapping: |
| 372 | yield key |
| 373 | |
| 374 | KeysView.register(type({}.keys())) |
| 375 | |
| 376 | |
| 377 | class ItemsView(MappingView, Set): |
| 378 | |
| 379 | def __contains__(self, item): |
| 380 | key, value = item |
| 381 | try: |
| 382 | v = self._mapping[key] |
| 383 | except KeyError: |
| 384 | return False |
| 385 | else: |
| 386 | return v == value |
| 387 | |
| 388 | def __iter__(self): |
| 389 | for key in self._mapping: |
| 390 | yield (key, self._mapping[key]) |
| 391 | |
| 392 | ItemsView.register(type({}.items())) |
| 393 | |
| 394 | |
| 395 | class ValuesView(MappingView): |
| 396 | |
| 397 | def __contains__(self, value): |
| 398 | for key in self._mapping: |
| 399 | if value == self._mapping[key]: |
| 400 | return True |
| 401 | return False |
| 402 | |
| 403 | def __iter__(self): |
| 404 | for key in self._mapping: |
| 405 | yield self._mapping[key] |
| 406 | |
| 407 | ValuesView.register(type({}.values())) |
| 408 | |
| 409 | |
| 410 | class MutableMapping(Mapping): |
| 411 | |
| 412 | @abstractmethod |
| 413 | def __setitem__(self, key, value): |
| 414 | raise KeyError |
| 415 | |
| 416 | @abstractmethod |
| 417 | def __delitem__(self, key): |
| 418 | raise KeyError |
| 419 | |
| 420 | __marker = object() |
| 421 | |
| 422 | def pop(self, key, default=__marker): |
| 423 | try: |
| 424 | value = self[key] |
| 425 | except KeyError: |
| 426 | if default is self.__marker: |
| 427 | raise |
| 428 | return default |
| 429 | else: |
| 430 | del self[key] |
| 431 | return value |
| 432 | |
| 433 | def popitem(self): |
| 434 | try: |
| 435 | key = next(iter(self)) |
| 436 | except StopIteration: |
| 437 | raise KeyError |
| 438 | value = self[key] |
| 439 | del self[key] |
| 440 | return key, value |
| 441 | |
| 442 | def clear(self): |
| 443 | try: |
| 444 | while True: |
| 445 | self.popitem() |
| 446 | except KeyError: |
| 447 | pass |
| 448 | |
| 449 | def update(self, other=(), **kwds): |
| 450 | if isinstance(other, Mapping): |
| 451 | for key in other: |
| 452 | self[key] = other[key] |
| 453 | elif hasattr(other, "keys"): |
| 454 | for key in other.keys(): |
| 455 | self[key] = other[key] |
| 456 | else: |
| 457 | for key, value in other: |
| 458 | self[key] = value |
| 459 | for key, value in kwds.items(): |
| 460 | self[key] = value |
| 461 | |
| 462 | MutableMapping.register(dict) |
| 463 | |
| 464 | |
| 465 | ### SEQUENCES ### |
| 466 | |
| 467 | |
| 468 | class Sequence: |
| 469 | __metaclass__ = ABCMeta |
| 470 | |
| 471 | """All the operations on a read-only sequence. |
| 472 | |
| 473 | Concrete subclasses must override __new__ or __init__, |
| 474 | __getitem__, and __len__. |
| 475 | """ |
| 476 | |
| 477 | @abstractmethod |
| 478 | def __getitem__(self, index): |
| 479 | raise IndexError |
| 480 | |
| 481 | @abstractmethod |
| 482 | def __len__(self): |
| 483 | return 0 |
| 484 | |
| 485 | def __iter__(self): |
| 486 | i = 0 |
| 487 | while True: |
| 488 | try: |
| 489 | v = self[i] |
| 490 | except IndexError: |
| 491 | break |
| 492 | yield v |
| 493 | i += 1 |
| 494 | |
| 495 | def __contains__(self, value): |
| 496 | for v in self: |
| 497 | if v == value: |
| 498 | return True |
| 499 | return False |
| 500 | |
| 501 | def __reversed__(self): |
| 502 | for i in reversed(range(len(self))): |
| 503 | yield self[i] |
| 504 | |
| 505 | def index(self, value): |
| 506 | for i, v in enumerate(self): |
| 507 | if v == value: |
| 508 | return i |
| 509 | raise ValueError |
| 510 | |
| 511 | def count(self, value): |
| 512 | return sum(1 for v in self if v == value) |
| 513 | |
| 514 | Sequence.register(tuple) |
| 515 | Sequence.register(basestring) |
| 516 | Sequence.register(buffer) |
| 517 | |
| 518 | |
| 519 | class MutableSequence(Sequence): |
| 520 | |
| 521 | @abstractmethod |
| 522 | def __setitem__(self, index, value): |
| 523 | raise IndexError |
| 524 | |
| 525 | @abstractmethod |
| 526 | def __delitem__(self, index): |
| 527 | raise IndexError |
| 528 | |
| 529 | @abstractmethod |
| 530 | def insert(self, index, value): |
| 531 | raise IndexError |
| 532 | |
| 533 | def append(self, value): |
| 534 | self.insert(len(self), value) |
| 535 | |
| 536 | def reverse(self): |
| 537 | n = len(self) |
| 538 | for i in range(n//2): |
| 539 | self[i], self[n-i-1] = self[n-i-1], self[i] |
| 540 | |
| 541 | def extend(self, values): |
| 542 | for v in values: |
| 543 | self.append(v) |
| 544 | |
| 545 | def pop(self, index=-1): |
| 546 | v = self[index] |
| 547 | del self[index] |
| 548 | return v |
| 549 | |
| 550 | def remove(self, value): |
| 551 | del self[self.index(value)] |
| 552 | |
| 553 | def __iadd__(self, values): |
| 554 | self.extend(values) |
| 555 | |
| 556 | MutableSequence.register(list) |