1 # Copyright 2007 Google, Inc. All Rights Reserved.
2 # Licensed to PSF under a Contributor Agreement.
4 """Abstract Base Classes (ABCs) for collections, according to PEP 3119.
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.
11 from abc
import ABCMeta
, abstractmethod
13 __all__
= ["Hashable", "Iterable", "Iterator",
14 "Sized", "Container", "Callable",
16 "Mapping", "MutableMapping",
17 "MappingView", "KeysView", "ItemsView", "ValuesView",
18 "Sequence", "MutableSequence",
21 ### ONE-TRICK PONIES ###
24 __metaclass__
= ABCMeta
31 def __subclasshook__(cls
, C
):
34 if "__hash__" in B
.__dict
__:
35 if B
.__dict
__["__hash__"]:
42 __metaclass__
= ABCMeta
50 def __subclasshook__(cls
, C
):
52 if any("__iter__" in B
.__dict
__ for B
in C
.__mro
__):
56 Iterable
.register(str)
59 class Iterator(Iterable
):
69 def __subclasshook__(cls
, C
):
71 if any("next" in B
.__dict
__ for B
in C
.__mro
__):
77 __metaclass__
= ABCMeta
84 def __subclasshook__(cls
, C
):
86 if any("__len__" in B
.__dict
__ for B
in C
.__mro
__):
92 __metaclass__
= ABCMeta
95 def __contains__(self
, x
):
99 def __subclasshook__(cls
, C
):
101 if any("__contains__" in B
.__dict
__ for B
in C
.__mro
__):
103 return NotImplemented
107 __metaclass__
= ABCMeta
110 def __call__(self
, *args
, **kwds
):
114 def __subclasshook__(cls
, C
):
116 if any("__call__" in B
.__dict
__ for B
in C
.__mro
__):
118 return NotImplemented
124 class Set(Sized
, Iterable
, Container
):
125 """A set is a finite, iterable container.
127 This class provides concrete generic implementations of all
128 methods except for __contains__, __iter__ and __len__.
130 To override the comparisons (presumably for speed, as the
131 semantics are fixed), all you have to do is redefine __le__ and
132 then the other operations will automatically follow suit.
135 def __le__(self
, other
):
136 if not isinstance(other
, Set
):
137 return NotImplemented
138 if len(self
) > len(other
):
141 if elem
not in other
:
145 def __lt__(self
, other
):
146 if not isinstance(other
, Set
):
147 return NotImplemented
148 return len(self
) < len(other
) and self
.__le
__(other
)
150 def __gt__(self
, other
):
151 if not isinstance(other
, Set
):
152 return NotImplemented
155 def __ge__(self
, other
):
156 if not isinstance(other
, Set
):
157 return NotImplemented
160 def __eq__(self
, other
):
161 if not isinstance(other
, Set
):
162 return NotImplemented
163 return len(self
) == len(other
) and self
.__le
__(other
)
165 def __ne__(self
, other
):
166 return not (self
== other
)
169 def _from_iterable(cls
, it
):
170 '''Construct an instance of the class from any iterable input.
172 Must override this method if the class constructor signature
173 does not accept an iterable for an input.
177 def __and__(self
, other
):
178 if not isinstance(other
, Iterable
):
179 return NotImplemented
180 return self
._from
_iterable
(value
for value
in other
if value
in self
)
182 def isdisjoint(self
, other
):
188 def __or__(self
, other
):
189 if not isinstance(other
, Iterable
):
190 return NotImplemented
191 chain
= (e
for s
in (self
, other
) for e
in s
)
192 return self
._from
_iterable
(chain
)
194 def __sub__(self
, other
):
195 if not isinstance(other
, Set
):
196 if not isinstance(other
, Iterable
):
197 return NotImplemented
198 other
= self
._from
_iterable
(other
)
199 return self
._from
_iterable
(value
for value
in self
200 if value
not in other
)
202 def __xor__(self
, other
):
203 if not isinstance(other
, Set
):
204 if not isinstance(other
, Iterable
):
205 return NotImplemented
206 other
= self
._from
_iterable
(other
)
207 return (self
- other
) |
(other
- self
)
210 """Compute the hash value of a set.
212 Note that we don't define __hash__: not all sets are hashable.
213 But if you define a hashable set type, its __hash__ should
216 This must be compatible __eq__.
218 All sets ought to compare equal if they contain the same
219 elements, regardless of how they are implemented, and
220 regardless of the order of the elements; so there's not much
221 freedom for __eq__ or __hash__. We match the algorithm used
222 by the built-in frozenset type.
227 h
= 1927868237 * (n
+ 1)
231 h ^
= (hx ^
(hx
<< 16) ^
89869747) * 3644798167
233 h
= h
* 69069 + 907133923
241 Set
.register(frozenset)
244 class MutableSet(Set
):
247 def add(self
, value
):
248 """Return True if it was added, False if already there."""
249 raise NotImplementedError
252 def discard(self
, value
):
253 """Return True if it was deleted, False if not there."""
254 raise NotImplementedError
256 def remove(self
, value
):
257 """Remove an element. If not a member, raise a KeyError."""
258 if value
not in self
:
259 raise KeyError(value
)
263 """Return the popped value. Raise KeyError if empty."""
266 value
= it
.__next
__()
267 except StopIteration:
273 """This is slow (creates N new iterators!) but effective."""
280 def __ior__(self
, it
):
285 def __iand__(self
, c
):
291 def __ixor__(self
, it
):
292 if not isinstance(it
, Set
):
293 it
= self
._from
_iterable
(it
)
301 def __isub__(self
, it
):
306 MutableSet
.register(set)
312 class Mapping(Sized
, Iterable
, Container
):
315 def __getitem__(self
, key
):
318 def get(self
, key
, default
=None):
324 def __contains__(self
, key
):
333 return KeysView(self
)
336 return ItemsView(self
)
339 return ValuesView(self
)
341 def __eq__(self
, other
):
342 return isinstance(other
, Mapping
) and \
343 dict(self
.items()) == dict(other
.items())
345 def __ne__(self
, other
):
346 return not (self
== other
)
348 class MappingView(Sized
):
350 def __init__(self
, mapping
):
351 self
._mapping
= mapping
354 return len(self
._mapping
)
357 class KeysView(MappingView
, Set
):
359 def __contains__(self
, key
):
360 return key
in self
._mapping
363 for key
in self
._mapping
:
366 KeysView
.register(type({}.keys()))
369 class ItemsView(MappingView
, Set
):
371 def __contains__(self
, item
):
374 v
= self
._mapping
[key
]
381 for key
in self
._mapping
:
382 yield (key
, self
._mapping
[key
])
384 ItemsView
.register(type({}.items()))
387 class ValuesView(MappingView
):
389 def __contains__(self
, value
):
390 for key
in self
._mapping
:
391 if value
== self
._mapping
[key
]:
396 for key
in self
._mapping
:
397 yield self
._mapping
[key
]
399 ValuesView
.register(type({}.values()))
402 class MutableMapping(Mapping
):
405 def __setitem__(self
, key
, value
):
409 def __delitem__(self
, key
):
414 def pop(self
, key
, default
=__marker
):
418 if default
is self
.__marker
:
427 key
= next(iter(self
))
428 except StopIteration:
441 def update(self
, other
=(), **kwds
):
442 if isinstance(other
, Mapping
):
444 self
[key
] = other
[key
]
445 elif hasattr(other
, "keys"):
446 for key
in other
.keys():
447 self
[key
] = other
[key
]
449 for key
, value
in other
:
451 for key
, value
in kwds
.items():
454 def setdefault(self
, key
, default
=None):
461 MutableMapping
.register(dict)
467 class Sequence(Sized
, Iterable
, Container
):
468 """All the operations on a read-only sequence.
470 Concrete subclasses must override __new__ or __init__,
471 __getitem__, and __len__.
475 def __getitem__(self
, index
):
488 def __contains__(self
, value
):
494 def __reversed__(self
):
495 for i
in reversed(range(len(self
))):
498 def index(self
, value
):
499 for i
, v
in enumerate(self
):
504 def count(self
, value
):
505 return sum(1 for v
in self
if v
== value
)
507 Sequence
.register(tuple)
508 Sequence
.register(basestring
)
509 Sequence
.register(buffer)
512 class MutableSequence(Sequence
):
515 def __setitem__(self
, index
, value
):
519 def __delitem__(self
, index
):
523 def insert(self
, index
, value
):
526 def append(self
, value
):
527 self
.insert(len(self
), value
)
531 for i
in range(n
//2):
532 self
[i
], self
[n
-i
-1] = self
[n
-i
-1], self
[i
]
534 def extend(self
, values
):
538 def pop(self
, index
=-1):
543 def remove(self
, value
):
544 del self
[self
.index(value
)]
546 def __iadd__(self
, values
):
549 MutableSequence
.register(list)