test_iterlen.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. """ Test Iterator Length Transparency
  2. Some functions or methods which accept general iterable arguments have
  3. optional, more efficient code paths if they know how many items to expect.
  4. For instance, map(func, iterable), will pre-allocate the exact amount of
  5. space required whenever the iterable can report its length.
  6. The desired invariant is: len(it)==len(list(it)).
  7. A complication is that an iterable and iterator can be the same object. To
  8. maintain the invariant, an iterator needs to dynamically update its length.
  9. For instance, an iterable such as xrange(10) always reports its length as ten,
  10. but it=iter(xrange(10)) starts at ten, and then goes to nine after it.next().
  11. Having this capability means that map() can ignore the distinction between
  12. map(func, iterable) and map(func, iter(iterable)).
  13. When the iterable is immutable, the implementation can straight-forwardly
  14. report the original length minus the cumulative number of calls to next().
  15. This is the case for tuples, xrange objects, and itertools.repeat().
  16. Some containers become temporarily immutable during iteration. This includes
  17. dicts, sets, and collections.deque. Their implementation is equally simple
  18. though they need to permanently set their length to zero whenever there is
  19. an attempt to iterate after a length mutation.
  20. The situation slightly more involved whenever an object allows length mutation
  21. during iteration. Lists and sequence iterators are dynamically updatable.
  22. So, if a list is extended during iteration, the iterator will continue through
  23. the new items. If it shrinks to a point before the most recent iteration,
  24. then no further items are available and the length is reported at zero.
  25. Reversed objects can also be wrapped around mutable objects; however, any
  26. appends after the current position are ignored. Any other approach leads
  27. to confusion and possibly returning the same item more than once.
  28. The iterators not listed above, such as enumerate and the other itertools,
  29. are not length transparent because they have no way to distinguish between
  30. iterables that report static length and iterators whose length changes with
  31. each call (i.e. the difference between enumerate('abc') and
  32. enumerate(iter('abc')).
  33. """
  34. import unittest
  35. from test import test_support
  36. from itertools import repeat
  37. from collections import deque
  38. from __builtin__ import len as _len
  39. n = 10
  40. def len(obj):
  41. try:
  42. return _len(obj)
  43. except TypeError:
  44. try:
  45. # note: this is an internal undocumented API,
  46. # don't rely on it in your own programs
  47. return obj.__length_hint__()
  48. except AttributeError:
  49. raise TypeError
  50. class TestInvariantWithoutMutations(unittest.TestCase):
  51. def test_invariant(self):
  52. it = self.it
  53. for i in reversed(xrange(1, n+1)):
  54. self.assertEqual(len(it), i)
  55. it.next()
  56. self.assertEqual(len(it), 0)
  57. self.assertRaises(StopIteration, it.next)
  58. self.assertEqual(len(it), 0)
  59. class TestTemporarilyImmutable(TestInvariantWithoutMutations):
  60. def test_immutable_during_iteration(self):
  61. # objects such as deques, sets, and dictionaries enforce
  62. # length immutability during iteration
  63. it = self.it
  64. self.assertEqual(len(it), n)
  65. it.next()
  66. self.assertEqual(len(it), n-1)
  67. self.mutate()
  68. self.assertRaises(RuntimeError, it.next)
  69. self.assertEqual(len(it), 0)
  70. ## ------- Concrete Type Tests -------
  71. class TestRepeat(TestInvariantWithoutMutations):
  72. def setUp(self):
  73. self.it = repeat(None, n)
  74. def test_no_len_for_infinite_repeat(self):
  75. # The repeat() object can also be infinite
  76. self.assertRaises(TypeError, len, repeat(None))
  77. class TestXrange(TestInvariantWithoutMutations):
  78. def setUp(self):
  79. self.it = iter(xrange(n))
  80. class TestXrangeCustomReversed(TestInvariantWithoutMutations):
  81. def setUp(self):
  82. self.it = reversed(xrange(n))
  83. class TestTuple(TestInvariantWithoutMutations):
  84. def setUp(self):
  85. self.it = iter(tuple(xrange(n)))
  86. ## ------- Types that should not be mutated during iteration -------
  87. class TestDeque(TestTemporarilyImmutable):
  88. def setUp(self):
  89. d = deque(xrange(n))
  90. self.it = iter(d)
  91. self.mutate = d.pop
  92. class TestDequeReversed(TestTemporarilyImmutable):
  93. def setUp(self):
  94. d = deque(xrange(n))
  95. self.it = reversed(d)
  96. self.mutate = d.pop
  97. class TestDictKeys(TestTemporarilyImmutable):
  98. def setUp(self):
  99. d = dict.fromkeys(xrange(n))
  100. self.it = iter(d)
  101. self.mutate = d.popitem
  102. class TestDictItems(TestTemporarilyImmutable):
  103. def setUp(self):
  104. d = dict.fromkeys(xrange(n))
  105. self.it = d.iteritems()
  106. self.mutate = d.popitem
  107. class TestDictValues(TestTemporarilyImmutable):
  108. def setUp(self):
  109. d = dict.fromkeys(xrange(n))
  110. self.it = d.itervalues()
  111. self.mutate = d.popitem
  112. class TestSet(TestTemporarilyImmutable):
  113. def setUp(self):
  114. d = set(xrange(n))
  115. self.it = iter(d)
  116. self.mutate = d.pop
  117. ## ------- Types that can mutate during iteration -------
  118. class TestList(TestInvariantWithoutMutations):
  119. def setUp(self):
  120. self.it = iter(range(n))
  121. def test_mutation(self):
  122. d = range(n)
  123. it = iter(d)
  124. it.next()
  125. it.next()
  126. self.assertEqual(len(it), n-2)
  127. d.append(n)
  128. self.assertEqual(len(it), n-1) # grow with append
  129. d[1:] = []
  130. self.assertEqual(len(it), 0)
  131. self.assertEqual(list(it), [])
  132. d.extend(xrange(20))
  133. self.assertEqual(len(it), 0)
  134. class TestListReversed(TestInvariantWithoutMutations):
  135. def setUp(self):
  136. self.it = reversed(range(n))
  137. def test_mutation(self):
  138. d = range(n)
  139. it = reversed(d)
  140. it.next()
  141. it.next()
  142. self.assertEqual(len(it), n-2)
  143. d.append(n)
  144. self.assertEqual(len(it), n-2) # ignore append
  145. d[1:] = []
  146. self.assertEqual(len(it), 0)
  147. self.assertEqual(list(it), []) # confirm invariant
  148. d.extend(xrange(20))
  149. self.assertEqual(len(it), 0)
  150. ## -- Check to make sure exceptions are not suppressed by __length_hint__()
  151. class BadLen(object):
  152. def __iter__(self): return iter(range(10))
  153. def __len__(self):
  154. raise RuntimeError('hello')
  155. class BadLengthHint(object):
  156. def __iter__(self): return iter(range(10))
  157. def __length_hint__(self):
  158. raise RuntimeError('hello')
  159. class NoneLengthHint(object):
  160. def __iter__(self): return iter(range(10))
  161. def __length_hint__(self):
  162. return None
  163. class TestLengthHintExceptions(unittest.TestCase):
  164. def test_issue1242657(self):
  165. self.assertRaises(RuntimeError, list, BadLen())
  166. self.assertRaises(RuntimeError, list, BadLengthHint())
  167. self.assertRaises(RuntimeError, [].extend, BadLen())
  168. self.assertRaises(RuntimeError, [].extend, BadLengthHint())
  169. self.assertRaises(RuntimeError, zip, BadLen())
  170. self.assertRaises(RuntimeError, zip, BadLengthHint())
  171. self.assertRaises(RuntimeError, filter, None, BadLen())
  172. self.assertRaises(RuntimeError, filter, None, BadLengthHint())
  173. self.assertRaises(RuntimeError, map, chr, BadLen())
  174. self.assertRaises(RuntimeError, map, chr, BadLengthHint())
  175. b = bytearray(range(10))
  176. self.assertRaises(RuntimeError, b.extend, BadLen())
  177. self.assertRaises(RuntimeError, b.extend, BadLengthHint())
  178. def test_invalid_hint(self):
  179. # Make sure an invalid result doesn't muck-up the works
  180. self.assertEqual(list(NoneLengthHint()), list(range(10)))
  181. def test_main():
  182. unittests = [
  183. TestRepeat,
  184. TestXrange,
  185. TestXrangeCustomReversed,
  186. TestTuple,
  187. TestDeque,
  188. TestDequeReversed,
  189. TestDictKeys,
  190. TestDictItems,
  191. TestDictValues,
  192. TestSet,
  193. TestList,
  194. TestListReversed,
  195. TestLengthHintExceptions,
  196. ]
  197. test_support.run_unittest(*unittests)
  198. if __name__ == "__main__":
  199. test_main()