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)
60 __metaclass__
= ABCMeta
70 def __subclasshook__(cls
, C
):
72 if any("next" in B
.__dict
__ for B
in C
.__mro
__):
78 __metaclass__
= ABCMeta
85 def __subclasshook__(cls
, C
):
87 if any("__len__" in B
.__dict
__ for B
in C
.__mro
__):
93 __metaclass__
= ABCMeta
96 def __contains__(self
, x
):
100 def __subclasshook__(cls
, C
):
102 if any("__contains__" in B
.__dict
__ for B
in C
.__mro
__):
104 return NotImplemented
108 __metaclass__
= ABCMeta
111 def __contains__(self
, x
):
115 def __subclasshook__(cls
, C
):
117 if any("__call__" in B
.__dict
__ for B
in C
.__mro
__):
119 return NotImplemented
126 __metaclass__
= ABCMeta
128 """A set is a finite, iterable container.
130 This class provides concrete generic implementations of all
131 methods except for __contains__, __iter__ and __len__.
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.
139 def __contains__(self
, value
):
151 def __le__(self
, other
):
152 if not isinstance(other
, Set
):
153 return NotImplemented
154 if len(self
) > len(other
):
157 if elem
not in other
:
161 def __lt__(self
, other
):
162 if not isinstance(other
, Set
):
163 return NotImplemented
164 return len(self
) < len(other
) and self
.__le
__(other
)
166 def __eq__(self
, other
):
167 if not isinstance(other
, Set
):
168 return NotImplemented
169 return len(self
) == len(other
) and self
.__le
__(other
)
172 def _from_iterable(cls
, it
):
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
)
180 def __or__(self
, other
):
181 if not isinstance(other
, Iterable
):
182 return NotImplemented
183 return self
._from
_iterable
(itertools
.chain(self
, other
))
185 def __sub__(self
, other
):
186 if not isinstance(other
, Set
):
187 if not isinstance(other
, Iterable
):
188 return NotImplemented
189 other
= self
._from
_iterable
(other
)
190 return self
._from
_iterable
(value
for value
in self
191 if value
not in other
)
193 def __xor__(self
, other
):
194 if not isinstance(other
, Set
):
195 if not isinstance(other
, Iterable
):
196 return NotImplemented
197 other
= self
._from
_iterable
(other
)
198 return (self
- other
) |
(other
- self
)
201 """Compute the hash value of a set.
203 Note that we don't define __hash__: not all sets are hashable.
204 But if you define a hashable set type, its __hash__ should
207 This must be compatible __eq__.
209 All sets ought to compare equal if they contain the same
210 elements, regardless of how they are implemented, and
211 regardless of the order of the elements; so there's not much
212 freedom for __eq__ or __hash__. We match the algorithm used
213 by the built-in frozenset type.
218 h
= 1927868237 * (n
+ 1)
222 h ^
= (hx ^
(hx
<< 16) ^
89869747) * 3644798167
224 h
= h
* 69069 + 907133923
232 Set
.register(frozenset)
235 class MutableSet(Set
):
238 def add(self
, value
):
239 """Return True if it was added, False if already there."""
240 raise NotImplementedError
243 def discard(self
, value
):
244 """Return True if it was deleted, False if not there."""
245 raise NotImplementedError
248 """Return the popped value. Raise KeyError if empty."""
251 value
= it
.__next
__()
252 except StopIteration:
257 def toggle(self
, value
):
258 """Return True if it was added, False if deleted."""
259 # XXX This implementation is not thread-safe
268 """This is slow (creates N new iterators!) but effective."""
275 def __ior__(self
, it
):
280 def __iand__(self
, c
):
286 def __ixor__(self
, it
):
287 # This calls toggle(), so if that is overridded, we call the override
292 def __isub__(self
, it
):
297 MutableSet
.register(set)
304 __metaclass__
= ABCMeta
307 def __getitem__(self
, key
):
310 def get(self
, key
, default
=None):
316 def __contains__(self
, key
):
334 return KeysView(self
)
337 return ItemsView(self
)
340 return ValuesView(self
)
344 __metaclass__
= ABCMeta
346 def __init__(self
, mapping
):
347 self
._mapping
= mapping
350 return len(self
._mapping
)
353 class KeysView(MappingView
, Set
):
355 def __contains__(self
, key
):
356 return key
in self
._mapping
359 for key
in self
._mapping
:
362 KeysView
.register(type({}.keys()))
365 class ItemsView(MappingView
, Set
):
367 def __contains__(self
, item
):
370 v
= self
._mapping
[key
]
377 for key
in self
._mapping
:
378 yield (key
, self
._mapping
[key
])
380 ItemsView
.register(type({}.items()))
383 class ValuesView(MappingView
):
385 def __contains__(self
, value
):
386 for key
in self
._mapping
:
387 if value
== self
._mapping
[key
]:
392 for key
in self
._mapping
:
393 yield self
._mapping
[key
]
395 ValuesView
.register(type({}.values()))
398 class MutableMapping(Mapping
):
401 def __setitem__(self
, key
, value
):
405 def __delitem__(self
, key
):
410 def pop(self
, key
, default
=__marker
):
414 if default
is self
.__marker
:
423 key
= next(iter(self
))
424 except StopIteration:
437 def update(self
, other
=(), **kwds
):
438 if isinstance(other
, Mapping
):
440 self
[key
] = other
[key
]
441 elif hasattr(other
, "keys"):
442 for key
in other
.keys():
443 self
[key
] = other
[key
]
445 for key
, value
in other
:
447 for key
, value
in kwds
.items():
450 MutableMapping
.register(dict)
457 __metaclass__
= ABCMeta
459 """All the operations on a read-only sequence.
461 Concrete subclasses must override __new__ or __init__,
462 __getitem__, and __len__.
466 def __getitem__(self
, index
):
483 def __contains__(self
, value
):
489 def __reversed__(self
):
490 for i
in reversed(range(len(self
))):
493 def index(self
, value
):
494 for i
, v
in enumerate(self
):
499 def count(self
, value
):
500 return sum(1 for v
in self
if v
== value
)
502 Sequence
.register(tuple)
503 Sequence
.register(basestring
)
504 Sequence
.register(buffer)
507 class MutableSequence(Sequence
):
510 def __setitem__(self
, index
, value
):
514 def __delitem__(self
, index
):
518 def insert(self
, index
, value
):
521 def append(self
, value
):
522 self
.insert(len(self
), value
)
526 for i
in range(n
//2):
527 self
[i
], self
[n
-i
-1] = self
[n
-i
-1], self
[i
]
529 def extend(self
, values
):
533 def pop(self
, index
=-1):
538 def remove(self
, value
):
539 del self
[self
.index(value
)]
541 def __iadd__(self
, values
):
544 MutableSequence
.register(list)