/Lib/_abcoll.py

http://unladen-swallow.googlecode.com/ · Python · 562 lines · 366 code · 6 blank · 190 comment · 13 complexity · c1e7cb1dda1bb39c6e8a4ed98705b209 MD5 · raw file

  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. DON'T USE THIS MODULE DIRECTLY! The classes here should be imported
  5. via collections; they are defined here only to alleviate certain
  6. bootstrapping issues. Unit tests are in test_collections.
  7. """
  8. from abc import ABCMeta, abstractmethod
  9. import sys
  10. __all__ = ["Hashable", "Iterable", "Iterator",
  11. "Sized", "Container", "Callable",
  12. "Set", "MutableSet",
  13. "Mapping", "MutableMapping",
  14. "MappingView", "KeysView", "ItemsView", "ValuesView",
  15. "Sequence", "MutableSequence",
  16. ]
  17. ### ONE-TRICK PONIES ###
  18. class Hashable:
  19. __metaclass__ = ABCMeta
  20. @abstractmethod
  21. def __hash__(self):
  22. return 0
  23. @classmethod
  24. def __subclasshook__(cls, C):
  25. if cls is Hashable:
  26. for B in C.__mro__:
  27. if "__hash__" in B.__dict__:
  28. if B.__dict__["__hash__"]:
  29. return True
  30. break
  31. return NotImplemented
  32. class Iterable:
  33. __metaclass__ = ABCMeta
  34. @abstractmethod
  35. def __iter__(self):
  36. while False:
  37. yield None
  38. @classmethod
  39. def __subclasshook__(cls, C):
  40. if cls is Iterable:
  41. if any("__iter__" in B.__dict__ for B in C.__mro__):
  42. return True
  43. return NotImplemented
  44. Iterable.register(str)
  45. class Iterator(Iterable):
  46. @abstractmethod
  47. def next(self):
  48. raise StopIteration
  49. def __iter__(self):
  50. return self
  51. @classmethod
  52. def __subclasshook__(cls, C):
  53. if cls is Iterator:
  54. if any("next" in B.__dict__ for B in C.__mro__):
  55. return True
  56. return NotImplemented
  57. class Sized:
  58. __metaclass__ = ABCMeta
  59. @abstractmethod
  60. def __len__(self):
  61. return 0
  62. @classmethod
  63. def __subclasshook__(cls, C):
  64. if cls is Sized:
  65. if any("__len__" in B.__dict__ for B in C.__mro__):
  66. return True
  67. return NotImplemented
  68. class Container:
  69. __metaclass__ = ABCMeta
  70. @abstractmethod
  71. def __contains__(self, x):
  72. return False
  73. @classmethod
  74. def __subclasshook__(cls, C):
  75. if cls is Container:
  76. if any("__contains__" in B.__dict__ for B in C.__mro__):
  77. return True
  78. return NotImplemented
  79. class Callable:
  80. __metaclass__ = ABCMeta
  81. @abstractmethod
  82. def __call__(self, *args, **kwds):
  83. return False
  84. @classmethod
  85. def __subclasshook__(cls, C):
  86. if cls is Callable:
  87. if any("__call__" in B.__dict__ for B in C.__mro__):
  88. return True
  89. return NotImplemented
  90. ### SETS ###
  91. class Set(Sized, Iterable, Container):
  92. """A set is a finite, iterable container.
  93. This class provides concrete generic implementations of all
  94. methods except for __contains__, __iter__ and __len__.
  95. To override the comparisons (presumably for speed, as the
  96. semantics are fixed), all you have to do is redefine __le__ and
  97. then the other operations will automatically follow suit.
  98. """
  99. def __le__(self, other):
  100. if not isinstance(other, Set):
  101. return NotImplemented
  102. if len(self) > len(other):
  103. return False
  104. for elem in self:
  105. if elem not in other:
  106. return False
  107. return True
  108. def __lt__(self, other):
  109. if not isinstance(other, Set):
  110. return NotImplemented
  111. return len(self) < len(other) and self.__le__(other)
  112. def __gt__(self, other):
  113. if not isinstance(other, Set):
  114. return NotImplemented
  115. return other < self
  116. def __ge__(self, other):
  117. if not isinstance(other, Set):
  118. return NotImplemented
  119. return other <= self
  120. def __eq__(self, other):
  121. if not isinstance(other, Set):
  122. return NotImplemented
  123. return len(self) == len(other) and self.__le__(other)
  124. def __ne__(self, other):
  125. return not (self == other)
  126. @classmethod
  127. def _from_iterable(cls, it):
  128. '''Construct an instance of the class from any iterable input.
  129. Must override this method if the class constructor signature
  130. does not accept an iterable for an input.
  131. '''
  132. return cls(it)
  133. def __and__(self, other):
  134. if not isinstance(other, Iterable):
  135. return NotImplemented
  136. return self._from_iterable(value for value in other if value in self)
  137. def isdisjoint(self, other):
  138. for value in other:
  139. if value in self:
  140. return False
  141. return True
  142. def __or__(self, other):
  143. if not isinstance(other, Iterable):
  144. return NotImplemented
  145. chain = (e for s in (self, other) for e in s)
  146. return self._from_iterable(chain)
  147. def __sub__(self, other):
  148. if not isinstance(other, Set):
  149. if not isinstance(other, Iterable):
  150. return NotImplemented
  151. other = self._from_iterable(other)
  152. return self._from_iterable(value for value in self
  153. if value not in other)
  154. def __xor__(self, other):
  155. if not isinstance(other, Set):
  156. if not isinstance(other, Iterable):
  157. return NotImplemented
  158. other = self._from_iterable(other)
  159. return (self - other) | (other - self)
  160. # Sets are not hashable by default, but subclasses can change this
  161. __hash__ = None
  162. def _hash(self):
  163. """Compute the hash value of a set.
  164. Note that we don't define __hash__: not all sets are hashable.
  165. But if you define a hashable set type, its __hash__ should
  166. call this function.
  167. This must be compatible __eq__.
  168. All sets ought to compare equal if they contain the same
  169. elements, regardless of how they are implemented, and
  170. regardless of the order of the elements; so there's not much
  171. freedom for __eq__ or __hash__. We match the algorithm used
  172. by the built-in frozenset type.
  173. """
  174. MAX = sys.maxint
  175. MASK = 2 * MAX + 1
  176. n = len(self)
  177. h = 1927868237 * (n + 1)
  178. h &= MASK
  179. for x in self:
  180. hx = hash(x)
  181. h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
  182. h &= MASK
  183. h = h * 69069 + 907133923
  184. h &= MASK
  185. if h > MAX:
  186. h -= MASK + 1
  187. if h == -1:
  188. h = 590923713
  189. return h
  190. Set.register(frozenset)
  191. class MutableSet(Set):
  192. @abstractmethod
  193. def add(self, value):
  194. """Add an element."""
  195. raise NotImplementedError
  196. @abstractmethod
  197. def discard(self, value):
  198. """Remove an element. Do not raise an exception if absent."""
  199. raise NotImplementedError
  200. def remove(self, value):
  201. """Remove an element. If not a member, raise a KeyError."""
  202. if value not in self:
  203. raise KeyError(value)
  204. self.discard(value)
  205. def pop(self):
  206. """Return the popped value. Raise KeyError if empty."""
  207. it = iter(self)
  208. try:
  209. value = next(it)
  210. except StopIteration:
  211. raise KeyError
  212. self.discard(value)
  213. return value
  214. def clear(self):
  215. """This is slow (creates N new iterators!) but effective."""
  216. try:
  217. while True:
  218. self.pop()
  219. except KeyError:
  220. pass
  221. def __ior__(self, it):
  222. for value in it:
  223. self.add(value)
  224. return self
  225. def __iand__(self, it):
  226. for value in (self - it):
  227. self.discard(value)
  228. return self
  229. def __ixor__(self, it):
  230. if not isinstance(it, Set):
  231. it = self._from_iterable(it)
  232. for value in it:
  233. if value in self:
  234. self.discard(value)
  235. else:
  236. self.add(value)
  237. return self
  238. def __isub__(self, it):
  239. for value in it:
  240. self.discard(value)
  241. return self
  242. MutableSet.register(set)
  243. ### MAPPINGS ###
  244. class Mapping(Sized, Iterable, Container):
  245. @abstractmethod
  246. def __getitem__(self, key):
  247. raise KeyError
  248. def get(self, key, default=None):
  249. try:
  250. return self[key]
  251. except KeyError:
  252. return default
  253. def __contains__(self, key):
  254. try:
  255. self[key]
  256. except KeyError:
  257. return False
  258. else:
  259. return True
  260. def iterkeys(self):
  261. return iter(self)
  262. def itervalues(self):
  263. for key in self:
  264. yield self[key]
  265. def iteritems(self):
  266. for key in self:
  267. yield (key, self[key])
  268. def keys(self):
  269. return list(self)
  270. def items(self):
  271. return [(key, self[key]) for key in self]
  272. def values(self):
  273. return [self[key] for key in self]
  274. # Mappings are not hashable by default, but subclasses can change this
  275. __hash__ = None
  276. def __eq__(self, other):
  277. return isinstance(other, Mapping) and \
  278. dict(self.items()) == dict(other.items())
  279. def __ne__(self, other):
  280. return not (self == other)
  281. class MappingView(Sized):
  282. def __init__(self, mapping):
  283. self._mapping = mapping
  284. def __len__(self):
  285. return len(self._mapping)
  286. class KeysView(MappingView, Set):
  287. def __contains__(self, key):
  288. return key in self._mapping
  289. def __iter__(self):
  290. for key in self._mapping:
  291. yield key
  292. class ItemsView(MappingView, Set):
  293. def __contains__(self, item):
  294. key, value = item
  295. try:
  296. v = self._mapping[key]
  297. except KeyError:
  298. return False
  299. else:
  300. return v == value
  301. def __iter__(self):
  302. for key in self._mapping:
  303. yield (key, self._mapping[key])
  304. class ValuesView(MappingView):
  305. def __contains__(self, value):
  306. for key in self._mapping:
  307. if value == self._mapping[key]:
  308. return True
  309. return False
  310. def __iter__(self):
  311. for key in self._mapping:
  312. yield self._mapping[key]
  313. class MutableMapping(Mapping):
  314. @abstractmethod
  315. def __setitem__(self, key, value):
  316. raise KeyError
  317. @abstractmethod
  318. def __delitem__(self, key):
  319. raise KeyError
  320. __marker = object()
  321. def pop(self, key, default=__marker):
  322. try:
  323. value = self[key]
  324. except KeyError:
  325. if default is self.__marker:
  326. raise
  327. return default
  328. else:
  329. del self[key]
  330. return value
  331. def popitem(self):
  332. try:
  333. key = next(iter(self))
  334. except StopIteration:
  335. raise KeyError
  336. value = self[key]
  337. del self[key]
  338. return key, value
  339. def clear(self):
  340. try:
  341. while True:
  342. self.popitem()
  343. except KeyError:
  344. pass
  345. def update(self, other=(), **kwds):
  346. if isinstance(other, Mapping):
  347. for key in other:
  348. self[key] = other[key]
  349. elif hasattr(other, "keys"):
  350. for key in other.keys():
  351. self[key] = other[key]
  352. else:
  353. for key, value in other:
  354. self[key] = value
  355. for key, value in kwds.items():
  356. self[key] = value
  357. def setdefault(self, key, default=None):
  358. try:
  359. return self[key]
  360. except KeyError:
  361. self[key] = default
  362. return default
  363. MutableMapping.register(dict)
  364. ### SEQUENCES ###
  365. class Sequence(Sized, Iterable, Container):
  366. """All the operations on a read-only sequence.
  367. Concrete subclasses must override __new__ or __init__,
  368. __getitem__, and __len__.
  369. """
  370. @abstractmethod
  371. def __getitem__(self, index):
  372. raise IndexError
  373. def __iter__(self):
  374. i = 0
  375. try:
  376. while True:
  377. v = self[i]
  378. yield v
  379. i += 1
  380. except IndexError:
  381. return
  382. def __contains__(self, value):
  383. for v in self:
  384. if v == value:
  385. return True
  386. return False
  387. def __reversed__(self):
  388. for i in reversed(range(len(self))):
  389. yield self[i]
  390. def index(self, value):
  391. for i, v in enumerate(self):
  392. if v == value:
  393. return i
  394. raise ValueError
  395. def count(self, value):
  396. return sum(1 for v in self if v == value)
  397. Sequence.register(tuple)
  398. Sequence.register(basestring)
  399. Sequence.register(buffer)
  400. Sequence.register(xrange)
  401. class MutableSequence(Sequence):
  402. @abstractmethod
  403. def __setitem__(self, index, value):
  404. raise IndexError
  405. @abstractmethod
  406. def __delitem__(self, index):
  407. raise IndexError
  408. @abstractmethod
  409. def insert(self, index, value):
  410. raise IndexError
  411. def append(self, value):
  412. self.insert(len(self), value)
  413. def reverse(self):
  414. n = len(self)
  415. for i in range(n//2):
  416. self[i], self[n-i-1] = self[n-i-1], self[i]
  417. def extend(self, values):
  418. for v in values:
  419. self.append(v)
  420. def pop(self, index=-1):
  421. v = self[index]
  422. del self[index]
  423. return v
  424. def remove(self, value):
  425. del self[self.index(value)]
  426. def __iadd__(self, values):
  427. self.extend(values)
  428. return self
  429. MutableSequence.register(list)