test_iterlen.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 range(10) always reports its length as ten,
  10. but it=iter(range(10)) starts at ten, and then goes to nine after next(it).
  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, range 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 itertools import repeat
  36. from collections import deque
  37. from operator import length_hint
  38. n = 10
  39. class TestInvariantWithoutMutations:
  40. def test_invariant(self):
  41. it = self.it
  42. for i in reversed(range(1, n+1)):
  43. self.assertEqual(length_hint(it), i)
  44. next(it)
  45. self.assertEqual(length_hint(it), 0)
  46. self.assertRaises(StopIteration, next, it)
  47. self.assertEqual(length_hint(it), 0)
  48. class TestTemporarilyImmutable(TestInvariantWithoutMutations):
  49. def test_immutable_during_iteration(self):
  50. # objects such as deques, sets, and dictionaries enforce
  51. # length immutability during iteration
  52. it = self.it
  53. self.assertEqual(length_hint(it), n)
  54. next(it)
  55. self.assertEqual(length_hint(it), n-1)
  56. self.mutate()
  57. self.assertRaises(RuntimeError, next, it)
  58. self.assertEqual(length_hint(it), 0)
  59. ## ------- Concrete Type Tests -------
  60. class TestRepeat(TestInvariantWithoutMutations, unittest.TestCase):
  61. def setUp(self):
  62. self.it = repeat(None, n)
  63. class TestXrange(TestInvariantWithoutMutations, unittest.TestCase):
  64. def setUp(self):
  65. self.it = iter(range(n))
  66. class TestXrangeCustomReversed(TestInvariantWithoutMutations, unittest.TestCase):
  67. def setUp(self):
  68. self.it = reversed(range(n))
  69. class TestTuple(TestInvariantWithoutMutations, unittest.TestCase):
  70. def setUp(self):
  71. self.it = iter(tuple(range(n)))
  72. ## ------- Types that should not be mutated during iteration -------
  73. class TestDeque(TestTemporarilyImmutable, unittest.TestCase):
  74. def setUp(self):
  75. d = deque(range(n))
  76. self.it = iter(d)
  77. self.mutate = d.pop
  78. class TestDequeReversed(TestTemporarilyImmutable, unittest.TestCase):
  79. def setUp(self):
  80. d = deque(range(n))
  81. self.it = reversed(d)
  82. self.mutate = d.pop
  83. class TestDictKeys(TestTemporarilyImmutable, unittest.TestCase):
  84. def setUp(self):
  85. d = dict.fromkeys(range(n))
  86. self.it = iter(d)
  87. self.mutate = d.popitem
  88. class TestDictItems(TestTemporarilyImmutable, unittest.TestCase):
  89. def setUp(self):
  90. d = dict.fromkeys(range(n))
  91. self.it = iter(d.items())
  92. self.mutate = d.popitem
  93. class TestDictValues(TestTemporarilyImmutable, unittest.TestCase):
  94. def setUp(self):
  95. d = dict.fromkeys(range(n))
  96. self.it = iter(d.values())
  97. self.mutate = d.popitem
  98. class TestSet(TestTemporarilyImmutable, unittest.TestCase):
  99. def setUp(self):
  100. d = set(range(n))
  101. self.it = iter(d)
  102. self.mutate = d.pop
  103. ## ------- Types that can mutate during iteration -------
  104. class TestList(TestInvariantWithoutMutations, unittest.TestCase):
  105. def setUp(self):
  106. self.it = iter(range(n))
  107. def test_mutation(self):
  108. d = list(range(n))
  109. it = iter(d)
  110. next(it)
  111. next(it)
  112. self.assertEqual(length_hint(it), n - 2)
  113. d.append(n)
  114. self.assertEqual(length_hint(it), n - 1) # grow with append
  115. d[1:] = []
  116. self.assertEqual(length_hint(it), 0)
  117. self.assertEqual(list(it), [])
  118. d.extend(range(20))
  119. self.assertEqual(length_hint(it), 0)
  120. class TestListReversed(TestInvariantWithoutMutations, unittest.TestCase):
  121. def setUp(self):
  122. self.it = reversed(range(n))
  123. def test_mutation(self):
  124. d = list(range(n))
  125. it = reversed(d)
  126. next(it)
  127. next(it)
  128. self.assertEqual(length_hint(it), n - 2)
  129. d.append(n)
  130. self.assertEqual(length_hint(it), n - 2) # ignore append
  131. d[1:] = []
  132. self.assertEqual(length_hint(it), 0)
  133. self.assertEqual(list(it), []) # confirm invariant
  134. d.extend(range(20))
  135. self.assertEqual(length_hint(it), 0)
  136. ## -- Check to make sure exceptions are not suppressed by __length_hint__()
  137. class BadLen(object):
  138. def __iter__(self):
  139. return iter(range(10))
  140. def __len__(self):
  141. raise RuntimeError('hello')
  142. class BadLengthHint(object):
  143. def __iter__(self):
  144. return iter(range(10))
  145. def __length_hint__(self):
  146. raise RuntimeError('hello')
  147. class NoneLengthHint(object):
  148. def __iter__(self):
  149. return iter(range(10))
  150. def __length_hint__(self):
  151. return NotImplemented
  152. class TestLengthHintExceptions(unittest.TestCase):
  153. def test_issue1242657(self):
  154. self.assertRaises(RuntimeError, list, BadLen())
  155. self.assertRaises(RuntimeError, list, BadLengthHint())
  156. self.assertRaises(RuntimeError, [].extend, BadLen())
  157. self.assertRaises(RuntimeError, [].extend, BadLengthHint())
  158. b = bytearray(range(10))
  159. self.assertRaises(RuntimeError, b.extend, BadLen())
  160. self.assertRaises(RuntimeError, b.extend, BadLengthHint())
  161. def test_invalid_hint(self):
  162. # Make sure an invalid result doesn't muck-up the works
  163. self.assertEqual(list(NoneLengthHint()), list(range(10)))
  164. if __name__ == "__main__":
  165. unittest.main()