Debian Codegraph @

lib-python/3/test/test_itertools.py

raw symbols SCIP
1 import doctest
2 import unittest
3 from test import support
4 from test.support import threading_helper
5 from itertools import *
6 import weakref
7 from decimal import Decimal
8 from fractions import Fraction
9 import operator
10 import random
11 import copy
12 import pickle
13 from functools import reduce
14 import sys
15 import struct
16 import threading
17 import gc
18
19 maxsize = support.MAX_Py_ssize_t
20 minsize = -maxsize-1
21
22 def lzip(*args):
23 return list(zip(*args))
24
25 def onearg(x):
26 'Test function of one argument'
27 return 2*x
28
29 def errfunc(*args):
30 'Test function that raises an error'
31 raise ValueError
32
33 def gen3():
34 'Non-restartable source sequence'
35 for i in (0, 1, 2):
36 yield i
37
38 def isEven(x):
39 'Test predicate'
40 return x%2==0
41
42 def isOdd(x):
43 'Test predicate'
44 return x%2==1
45
46 def tupleize(*args):
47 return args
48
49 def irange(n):
50 for i in range(n):
51 yield i
52
53 class StopNow:
54 'Class emulating an empty iterable.'
55 def __iter__(self):
56 return self
57 def __next__(self):
58 raise StopIteration
59
60 def take(n, seq):
61 'Convenience function for partially consuming a long of infinite iterable'
62 return list(islice(seq, n))
63
64 def prod(iterable):
65 return reduce(operator.mul, iterable, 1)
66
67 def fact(n):
68 'Factorial'
69 return prod(range(1, n+1))
70
71 # root level methods for pickling ability
72 def testR(r):
73 return r[0]
74
75 def testR2(r):
76 return r[2]
77
78 def underten(x):
79 return x<10
80
81 picklecopiers = [lambda s, proto=proto: pickle.loads(pickle.dumps(s, proto))
82 for proto in range(pickle.HIGHEST_PROTOCOL + 1)]
83
84 class TestBasicOps(unittest.TestCase):
85
86 def pickletest(self, protocol, it, stop=4, take=1, compare=None):
87 """Test that an iterator is the same after pickling, also when part-consumed"""
88 def expand(it, i=0):
89 # Recursively expand iterables, within sensible bounds
90 if i > 10:
91 raise RuntimeError("infinite recursion encountered")
92 if isinstance(it, str):
93 return it
94 try:
95 l = list(islice(it, stop))
96 except TypeError:
97 return it # can't expand it
98 return [expand(e, i+1) for e in l]
99
100 # Test the initial copy against the original
101 dump = pickle.dumps(it, protocol)
102 i2 = pickle.loads(dump)
103 self.assertEqual(type(it), type(i2))
104 a, b = expand(it), expand(i2)
105 self.assertEqual(a, b)
106 if compare:
107 c = expand(compare)
108 self.assertEqual(a, c)
109
110 # Take from the copy, and create another copy and compare them.
111 i3 = pickle.loads(dump)
112 took = 0
113 try:
114 for i in range(take):
115 next(i3)
116 took += 1
117 except StopIteration:
118 pass #in case there is less data than 'take'
119 dump = pickle.dumps(i3, protocol)
120 i4 = pickle.loads(dump)
121 a, b = expand(i3), expand(i4)
122 self.assertEqual(a, b)
123 if compare:
124 c = expand(compare[took:])
125 self.assertEqual(a, c);
126
127 def test_accumulate(self):
128 self.assertEqual(list(accumulate(range(10))), # one positional arg
129 [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
130 self.assertEqual(list(accumulate(iterable=range(10))), # kw arg
131 [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
132 for typ in int, complex, Decimal, Fraction: # multiple types
133 self.assertEqual(
134 list(accumulate(map(typ, range(10)))),
135 list(map(typ, [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])))
136 self.assertEqual(list(accumulate('abc')), ['a', 'ab', 'abc']) # works with non-numeric
137 self.assertEqual(list(accumulate([])), []) # empty iterable
138 self.assertEqual(list(accumulate([7])), [7]) # iterable of length one
139 self.assertRaises(TypeError, accumulate, range(10), 5, 6) # too many args
140 self.assertRaises(TypeError, accumulate) # too few args
141 self.assertRaises(TypeError, accumulate, x=range(10)) # unexpected kwd arg
142 self.assertRaises(TypeError, list, accumulate([1, []])) # args that don't add
143
144 s = [2, 8, 9, 5, 7, 0, 3, 4, 1, 6]
145 self.assertEqual(list(accumulate(s, min)),
146 [2, 2, 2, 2, 2, 0, 0, 0, 0, 0])
147 self.assertEqual(list(accumulate(s, max)),
148 [2, 8, 9, 9, 9, 9, 9, 9, 9, 9])
149 self.assertEqual(list(accumulate(s, operator.mul)),
150 [2, 16, 144, 720, 5040, 0, 0, 0, 0, 0])
151 with self.assertRaises(TypeError):
152 list(accumulate(s, chr)) # unary-operation
153 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
154 self.pickletest(proto, accumulate(range(10))) # test pickling
155 self.pickletest(proto, accumulate(range(10), initial=7))
156 self.assertEqual(list(accumulate([10, 5, 1], initial=None)), [10, 15, 16])
157 self.assertEqual(list(accumulate([10, 5, 1], initial=100)), [100, 110, 115, 116])
158 self.assertEqual(list(accumulate([], initial=100)), [100])
159 with self.assertRaises(TypeError):
160 list(accumulate([10, 20], 100))
161
162 def test_chain(self):
163
164 def chain2(*iterables):
165 'Pure python version in the docs'
166 for it in iterables:
167 for element in it:
168 yield element
169
170 for c in (chain, chain2):
171 self.assertEqual(list(c('abc', 'def')), list('abcdef'))
172 self.assertEqual(list(c('abc')), list('abc'))
173 self.assertEqual(list(c('')), [])
174 self.assertEqual(take(4, c('abc', 'def')), list('abcd'))
175 self.assertRaises(TypeError, list,c(2, 3))
176
177 def test_chain_from_iterable(self):
178 self.assertEqual(list(chain.from_iterable(['abc', 'def'])), list('abcdef'))
179 self.assertEqual(list(chain.from_iterable(['abc'])), list('abc'))
180 self.assertEqual(list(chain.from_iterable([''])), [])
181 self.assertEqual(take(4, chain.from_iterable(['abc', 'def'])), list('abcd'))
182 self.assertRaises(TypeError, list, chain.from_iterable([2, 3]))
183
184 def test_chain_reducible(self):
185 for oper in [copy.deepcopy] + picklecopiers:
186 it = chain('abc', 'def')
187 self.assertEqual(list(oper(it)), list('abcdef'))
188 self.assertEqual(next(it), 'a')
189 self.assertEqual(list(oper(it)), list('bcdef'))
190
191 self.assertEqual(list(oper(chain(''))), [])
192 self.assertEqual(take(4, oper(chain('abc', 'def'))), list('abcd'))
193 self.assertRaises(TypeError, list, oper(chain(2, 3)))
194 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
195 self.pickletest(proto, chain('abc', 'def'), compare=list('abcdef'))
196
197 @support.impl_detail("XXX chain.__setstate__ does not do all checks"
198 " on PyPy, will just complain later (but could"
199 " be fixed if important)")
200 def test_chain_setstate(self):
201 self.assertRaises(TypeError, chain().__setstate__, ())
202 self.assertRaises(TypeError, chain().__setstate__, [])
203 self.assertRaises(TypeError, chain().__setstate__, 0)
204 self.assertRaises(TypeError, chain().__setstate__, ([],))
205 self.assertRaises(TypeError, chain().__setstate__, (iter([]), []))
206 it = chain()
207 it.__setstate__((iter(['abc', 'def']),))
208 self.assertEqual(list(it), ['a', 'b', 'c', 'd', 'e', 'f'])
209 it = chain()
210 it.__setstate__((iter(['abc', 'def']), iter(['ghi'])))
211 self.assertEqual(list(it), ['ghi', 'a', 'b', 'c', 'd', 'e', 'f'])
212
213 def test_combinations(self):
214 self.assertRaises(TypeError, combinations, 'abc') # missing r argument
215 self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments
216 self.assertRaises(TypeError, combinations, None) # pool is not iterable
217 self.assertRaises(ValueError, combinations, 'abc', -2) # r is negative
218
219 for op in [lambda a:a] + picklecopiers:
220 self.assertEqual(list(op(combinations('abc', 32))), []) # r > n
221
222 self.assertEqual(list(op(combinations('ABCD', 2))),
223 [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
224 testIntermediate = combinations('ABCD', 2)
225 next(testIntermediate)
226 self.assertEqual(list(op(testIntermediate)),
227 [('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
228
229 self.assertEqual(list(op(combinations(range(4), 3))),
230 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
231 testIntermediate = combinations(range(4), 3)
232 next(testIntermediate)
233 self.assertEqual(list(op(testIntermediate)),
234 [(0,1,3), (0,2,3), (1,2,3)])
235
236
237 def combinations1(iterable, r):
238 'Pure python version shown in the docs'
239 pool = tuple(iterable)
240 n = len(pool)
241 if r > n:
242 return
243 indices = list(range(r))
244 yield tuple(pool[i] for i in indices)
245 while 1:
246 for i in reversed(range(r)):
247 if indices[i] != i + n - r:
248 break
249 else:
250 return
251 indices[i] += 1
252 for j in range(i+1, r):
253 indices[j] = indices[j-1] + 1
254 yield tuple(pool[i] for i in indices)
255
256 def combinations2(iterable, r):
257 'Pure python version shown in the docs'
258 pool = tuple(iterable)
259 n = len(pool)
260 for indices in permutations(range(n), r):
261 if sorted(indices) == list(indices):
262 yield tuple(pool[i] for i in indices)
263
264 def combinations3(iterable, r):
265 'Pure python version from cwr()'
266 pool = tuple(iterable)
267 n = len(pool)
268 for indices in combinations_with_replacement(range(n), r):
269 if len(set(indices)) == r:
270 yield tuple(pool[i] for i in indices)
271
272 for n in range(7):
273 values = [5*x-12 for x in range(n)]
274 for r in range(n+2):
275 result = list(combinations(values, r))
276 self.assertEqual(len(result), 0 if r>n else fact(n) / fact(r) / fact(n-r)) # right number of combs
277 self.assertEqual(len(result), len(set(result))) # no repeats
278 self.assertEqual(result, sorted(result)) # lexicographic order
279 for c in result:
280 self.assertEqual(len(c), r) # r-length combinations
281 self.assertEqual(len(set(c)), r) # no duplicate elements
282 self.assertEqual(list(c), sorted(c)) # keep original ordering
283 self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
284 self.assertEqual(list(c),
285 [e for e in values if e in c]) # comb is a subsequence of the input iterable
286 self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version
287 self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version
288 self.assertEqual(result, list(combinations3(values, r))) # matches second pure python version
289
290 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
291 self.pickletest(proto, combinations(values, r)) # test pickling
292
293 @support.bigaddrspacetest
294 def test_combinations_overflow(self):
295 with self.assertRaises((OverflowError, MemoryError)):
296 combinations("AA", 2**29)
297
298 # Test implementation detail: tuple re-use
299 @support.impl_detail("tuple reuse is specific to CPython")
300 def test_combinations_tuple_reuse(self):
301 self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1)
302 self.assertNotEqual(len(set(map(id, list(combinations('abcde', 3))))), 1)
303
304 def test_combinations_with_replacement(self):
305 cwr = combinations_with_replacement
306 self.assertRaises(TypeError, cwr, 'abc') # missing r argument
307 self.assertRaises(TypeError, cwr, 'abc', 2, 1) # too many arguments
308 self.assertRaises(TypeError, cwr, None) # pool is not iterable
309 self.assertRaises(ValueError, cwr, 'abc', -2) # r is negative
310
311 for op in [lambda a:a] + picklecopiers:
312 self.assertEqual(list(op(cwr('ABC', 2))),
313 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
314 testIntermediate = cwr('ABC', 2)
315 next(testIntermediate)
316 self.assertEqual(list(op(testIntermediate)),
317 [('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
318
319
320 def cwr1(iterable, r):
321 'Pure python version shown in the docs'
322 # number items returned: (n+r-1)! / r! / (n-1)! when n>0
323 pool = tuple(iterable)
324 n = len(pool)
325 if not n and r:
326 return
327 indices = [0] * r
328 yield tuple(pool[i] for i in indices)
329 while 1:
330 for i in reversed(range(r)):
331 if indices[i] != n - 1:
332 break
333 else:
334 return
335 indices[i:] = [indices[i] + 1] * (r - i)
336 yield tuple(pool[i] for i in indices)
337
338 def cwr2(iterable, r):
339 'Pure python version shown in the docs'
340 pool = tuple(iterable)
341 n = len(pool)
342 for indices in product(range(n), repeat=r):
343 if sorted(indices) == list(indices):
344 yield tuple(pool[i] for i in indices)
345
346 def numcombs(n, r):
347 if not n:
348 return 0 if r else 1
349 return fact(n+r-1) / fact(r)/ fact(n-1)
350
351 for n in range(7):
352 values = [5*x-12 for x in range(n)]
353 for r in range(n+2):
354 result = list(cwr(values, r))
355
356 self.assertEqual(len(result), numcombs(n, r)) # right number of combs
357 self.assertEqual(len(result), len(set(result))) # no repeats
358 self.assertEqual(result, sorted(result)) # lexicographic order
359
360 regular_combs = list(combinations(values, r)) # compare to combs without replacement
361 if n == 0 or r <= 1:
362 self.assertEqual(result, regular_combs) # cases that should be identical
363 else:
364 self.assertTrue(set(result) >= set(regular_combs)) # rest should be supersets of regular combs
365
366 for c in result:
367 self.assertEqual(len(c), r) # r-length combinations
368 noruns = [k for k,v in groupby(c)] # combo without consecutive repeats
369 self.assertEqual(len(noruns), len(set(noruns))) # no repeats other than consecutive
370 self.assertEqual(list(c), sorted(c)) # keep original ordering
371 self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
372 self.assertEqual(noruns,
373 [e for e in values if e in c]) # comb is a subsequence of the input iterable
374 self.assertEqual(result, list(cwr1(values, r))) # matches first pure python version
375 self.assertEqual(result, list(cwr2(values, r))) # matches second pure python version
376
377 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
378 self.pickletest(proto, cwr(values,r)) # test pickling
379
380 @support.bigaddrspacetest
381 def test_combinations_with_replacement_overflow(self):
382 with self.assertRaises((OverflowError, MemoryError)):
383 combinations_with_replacement("AA", 2**30)
384
385 # Test implementation detail: tuple re-use
386 @support.impl_detail("tuple reuse is specific to CPython")
387 def test_combinations_with_replacement_tuple_reuse(self):
388 cwr = combinations_with_replacement
389 self.assertEqual(len(set(map(id, cwr('abcde', 3)))), 1)
390 self.assertNotEqual(len(set(map(id, list(cwr('abcde', 3))))), 1)
391
392 def test_permutations(self):
393 self.assertRaises(TypeError, permutations) # too few arguments
394 self.assertRaises(TypeError, permutations, 'abc', 2, 1) # too many arguments
395 self.assertRaises(TypeError, permutations, None) # pool is not iterable
396 self.assertRaises(ValueError, permutations, 'abc', -2) # r is negative
397 self.assertEqual(list(permutations('abc', 32)), []) # r > n
398 self.assertRaises(TypeError, permutations, 'abc', 's') # r is not an int or None
399 self.assertEqual(list(permutations(range(3), 2)),
400 [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)])
401
402 def permutations1(iterable, r=None):
403 'Pure python version shown in the docs'
404 pool = tuple(iterable)
405 n = len(pool)
406 r = n if r is None else r
407 if r > n:
408 return
409 indices = list(range(n))
410 cycles = list(range(n-r+1, n+1))[::-1]
411 yield tuple(pool[i] for i in indices[:r])
412 while n:
413 for i in reversed(range(r)):
414 cycles[i] -= 1
415 if cycles[i] == 0:
416 indices[i:] = indices[i+1:] + indices[i:i+1]
417 cycles[i] = n - i
418 else:
419 j = cycles[i]
420 indices[i], indices[-j] = indices[-j], indices[i]
421 yield tuple(pool[i] for i in indices[:r])
422 break
423 else:
424 return
425
426 def permutations2(iterable, r=None):
427 'Pure python version shown in the docs'
428 pool = tuple(iterable)
429 n = len(pool)
430 r = n if r is None else r
431 for indices in product(range(n), repeat=r):
432 if len(set(indices)) == r:
433 yield tuple(pool[i] for i in indices)
434
435 for n in range(7):
436 values = [5*x-12 for x in range(n)]
437 for r in range(n+2):
438 result = list(permutations(values, r))
439 self.assertEqual(len(result), 0 if r>n else fact(n) / fact(n-r)) # right number of perms
440 self.assertEqual(len(result), len(set(result))) # no repeats
441 self.assertEqual(result, sorted(result)) # lexicographic order
442 for p in result:
443 self.assertEqual(len(p), r) # r-length permutations
444 self.assertEqual(len(set(p)), r) # no duplicate elements
445 self.assertTrue(all(e in values for e in p)) # elements taken from input iterable
446 self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version
447 self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version
448 if r == n:
449 self.assertEqual(result, list(permutations(values, None))) # test r as None
450 self.assertEqual(result, list(permutations(values))) # test default r
451
452 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
453 self.pickletest(proto, permutations(values, r)) # test pickling
454
455 @support.bigaddrspacetest
456 def test_permutations_overflow(self):
457 with self.assertRaises((OverflowError, MemoryError)):
458 permutations("A", 2**30)
459
460 @support.impl_detail("tuple reuse is specific to CPython")
461 def test_permutations_tuple_reuse(self):
462 self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1)
463 self.assertNotEqual(len(set(map(id, list(permutations('abcde', 3))))), 1)
464
465 def test_combinatorics(self):
466 # Test relationships between product(), permutations(),
467 # combinations() and combinations_with_replacement().
468
469 for n in range(6):
470 s = 'ABCDEFG'[:n]
471 for r in range(8):
472 prod = list(product(s, repeat=r))
473 cwr = list(combinations_with_replacement(s, r))
474 perm = list(permutations(s, r))
475 comb = list(combinations(s, r))
476
477 # Check size
478 self.assertEqual(len(prod), n**r)
479 self.assertEqual(len(cwr), (fact(n+r-1) / fact(r)/ fact(n-1)) if n else (not r))
480 self.assertEqual(len(perm), 0 if r>n else fact(n) / fact(n-r))
481 self.assertEqual(len(comb), 0 if r>n else fact(n) / fact(r) / fact(n-r))
482
483 # Check lexicographic order without repeated tuples
484 self.assertEqual(prod, sorted(set(prod)))
485 self.assertEqual(cwr, sorted(set(cwr)))
486 self.assertEqual(perm, sorted(set(perm)))
487 self.assertEqual(comb, sorted(set(comb)))
488
489 # Check interrelationships
490 self.assertEqual(cwr, [t for t in prod if sorted(t)==list(t)]) # cwr: prods which are sorted
491 self.assertEqual(perm, [t for t in prod if len(set(t))==r]) # perm: prods with no dups
492 self.assertEqual(comb, [t for t in perm if sorted(t)==list(t)]) # comb: perms that are sorted
493 self.assertEqual(comb, [t for t in cwr if len(set(t))==r]) # comb: cwrs without dups
494 self.assertEqual(comb, list(filter(set(cwr).__contains__, perm))) # comb: perm that is a cwr
495 self.assertEqual(comb, list(filter(set(perm).__contains__, cwr))) # comb: cwr that is a perm
496 self.assertEqual(comb, sorted(set(cwr) & set(perm))) # comb: both a cwr and a perm
497
498 def test_compress(self):
499 self.assertEqual(list(compress(data='ABCDEF', selectors=[1,0,1,0,1,1])), list('ACEF'))
500 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
501 self.assertEqual(list(compress('ABCDEF', [0,0,0,0,0,0])), list(''))
502 self.assertEqual(list(compress('ABCDEF', [1,1,1,1,1,1])), list('ABCDEF'))
503 self.assertEqual(list(compress('ABCDEF', [1,0,1])), list('AC'))
504 self.assertEqual(list(compress('ABC', [0,1,1,1,1,1])), list('BC'))
505 n = 10000
506 data = chain.from_iterable(repeat(range(6), n))
507 selectors = chain.from_iterable(repeat((0, 1)))
508 self.assertEqual(list(compress(data, selectors)), [1,3,5] * n)
509 self.assertRaises(TypeError, compress, None, range(6)) # 1st arg not iterable
510 self.assertRaises(TypeError, compress, range(6), None) # 2nd arg not iterable
511 self.assertRaises(TypeError, compress, range(6)) # too few args
512 self.assertRaises(TypeError, compress, range(6), None) # too many args
513
514 # check copy, deepcopy, pickle
515 for op in [lambda a:copy.copy(a), lambda a:copy.deepcopy(a)] + picklecopiers:
516 for data, selectors, result1, result2 in [
517 ('ABCDEF', [1,0,1,0,1,1], 'ACEF', 'CEF'),
518 ('ABCDEF', [0,0,0,0,0,0], '', ''),
519 ('ABCDEF', [1,1,1,1,1,1], 'ABCDEF', 'BCDEF'),
520 ('ABCDEF', [1,0,1], 'AC', 'C'),
521 ('ABC', [0,1,1,1,1,1], 'BC', 'C'),
522 ]:
523
524 self.assertEqual(list(op(compress(data=data, selectors=selectors))), list(result1))
525 self.assertEqual(list(op(compress(data, selectors))), list(result1))
526 testIntermediate = compress(data, selectors)
527 if result1:
528 next(testIntermediate)
529 self.assertEqual(list(op(testIntermediate)), list(result2))
530
531
532 def test_count(self):
533 self.assertEqual(lzip('abc',count()), [('a', 0), ('b', 1), ('c', 2)])
534 self.assertEqual(lzip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)])
535 self.assertEqual(take(2, lzip('abc',count(3))), [('a', 3), ('b', 4)])
536 self.assertEqual(take(2, zip('abc',count(-1))), [('a', -1), ('b', 0)])
537 self.assertEqual(take(2, zip('abc',count(-3))), [('a', -3), ('b', -2)])
538 self.assertRaises(TypeError, count, 2, 3, 4)
539 self.assertRaises(TypeError, count, 'a')
540 self.assertEqual(take(10, count(maxsize-5)),
541 list(range(maxsize-5, maxsize+5)))
542 self.assertEqual(take(10, count(-maxsize-5)),
543 list(range(-maxsize-5, -maxsize+5)))
544 self.assertEqual(take(3, count(3.25)), [3.25, 4.25, 5.25])
545 self.assertEqual(take(3, count(3.25-4j)), [3.25-4j, 4.25-4j, 5.25-4j])
546 self.assertEqual(take(3, count(Decimal('1.1'))),
547 [Decimal('1.1'), Decimal('2.1'), Decimal('3.1')])
548 self.assertEqual(take(3, count(Fraction(2, 3))),
549 [Fraction(2, 3), Fraction(5, 3), Fraction(8, 3)])
550 BIGINT = 1<<1000
551 self.assertEqual(take(3, count(BIGINT)), [BIGINT, BIGINT+1, BIGINT+2])
552 c = count(3)
553 self.assertEqual(repr(c), 'count(3)')
554 next(c)
555 self.assertEqual(repr(c), 'count(4)')
556 c = count(-9)
557 self.assertEqual(repr(c), 'count(-9)')
558 next(c)
559 self.assertEqual(next(c), -8)
560 self.assertEqual(repr(count(10.25)), 'count(10.25)')
561 self.assertEqual(repr(count(10.0)), 'count(10.0)')
562 self.assertEqual(type(next(count(10.0))), float)
563 for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5):
564 # Test repr
565 r1 = repr(count(i))
566 r2 = 'count(%r)'.__mod__(i)
567 self.assertEqual(r1, r2)
568
569 # check copy, deepcopy, pickle
570 for value in -3, 3, maxsize-5, maxsize+5:
571 c = count(value)
572 self.assertEqual(next(copy.copy(c)), value)
573 self.assertEqual(next(copy.deepcopy(c)), value)
574 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
575 self.pickletest(proto, count(value))
576
577 #check proper internal error handling for large "step' sizes
578 count(1, maxsize+5); sys.exc_info()
579
580 def test_count_with_stride(self):
581 self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
582 self.assertEqual(lzip('abc',count(start=2,step=3)),
583 [('a', 2), ('b', 5), ('c', 8)])
584 self.assertEqual(lzip('abc',count(step=-1)),
585 [('a', 0), ('b', -1), ('c', -2)])
586 self.assertRaises(TypeError, count, 'a', 'b')
587 self.assertEqual(lzip('abc',count(2,0)), [('a', 2), ('b', 2), ('c', 2)])
588 self.assertEqual(lzip('abc',count(2,1)), [('a', 2), ('b', 3), ('c', 4)])
589 self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
590 self.assertEqual(take(20, count(maxsize-15, 3)), take(20, range(maxsize-15, maxsize+100, 3)))
591 self.assertEqual(take(20, count(-maxsize-15, 3)), take(20, range(-maxsize-15,-maxsize+100, 3)))
592 self.assertEqual(take(3, count(10, maxsize+5)),
593 list(range(10, 10+3*(maxsize+5), maxsize+5)))
594 self.assertEqual(take(3, count(2, 1.25)), [2, 3.25, 4.5])
595 self.assertEqual(take(3, count(2, 3.25-4j)), [2, 5.25-4j, 8.5-8j])
596 self.assertEqual(take(3, count(Decimal('1.1'), Decimal('.1'))),
597 [Decimal('1.1'), Decimal('1.2'), Decimal('1.3')])
598 self.assertEqual(take(3, count(Fraction(2,3), Fraction(1,7))),
599 [Fraction(2,3), Fraction(17,21), Fraction(20,21)])
600 BIGINT = 1<<1000
601 self.assertEqual(take(3, count(step=BIGINT)), [0, BIGINT, 2*BIGINT])
602 self.assertEqual(repr(take(3, count(10, 2.5))), repr([10, 12.5, 15.0]))
603 c = count(3, 5)
604 self.assertEqual(repr(c), 'count(3, 5)')
605 next(c)
606 self.assertEqual(repr(c), 'count(8, 5)')
607 c = count(-9, 0)
608 self.assertEqual(repr(c), 'count(-9, 0)')
609 next(c)
610 self.assertEqual(repr(c), 'count(-9, 0)')
611 c = count(-9, -3)
612 self.assertEqual(repr(c), 'count(-9, -3)')
613 next(c)
614 self.assertEqual(repr(c), 'count(-12, -3)')
615 self.assertEqual(repr(c), 'count(-12, -3)')
616 self.assertEqual(repr(count(10.5, 1.25)), 'count(10.5, 1.25)')
617 self.assertEqual(repr(count(10.5, 1)), 'count(10.5)') # suppress step=1 when it's an int
618 self.assertEqual(repr(count(10.5, 1.00)), 'count(10.5, 1.0)') # do show float values lilke 1.0
619 self.assertEqual(repr(count(10, 1.00)), 'count(10, 1.0)')
620 c = count(10, 1.0)
621 self.assertEqual(type(next(c)), int)
622 self.assertEqual(type(next(c)), float)
623 for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5):
624 for j in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 1, 10, sys.maxsize-5, sys.maxsize+5):
625 # Test repr
626 r1 = repr(count(i, j))
627 if j == 1:
628 r2 = ('count(%r)' % i)
629 else:
630 r2 = ('count(%r, %r)' % (i, j))
631 self.assertEqual(r1, r2)
632 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
633 self.pickletest(proto, count(i, j))
634
635 def test_cycle(self):
636 self.assertEqual(take(10, cycle('abc')), list('abcabcabca'))
637 self.assertEqual(list(cycle('')), [])
638 self.assertRaises(TypeError, cycle)
639 self.assertRaises(TypeError, cycle, 5)
640 self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0])
641
642 def test_cycle_copy_pickle(self):
643 # check copy, deepcopy, pickle
644 c = cycle('abc')
645 self.assertEqual(next(c), 'a')
646 #simple copy currently not supported, because __reduce__ returns
647 #an internal iterator
648 #self.assertEqual(take(10, copy.copy(c)), list('bcabcabcab'))
649 self.assertEqual(take(10, copy.deepcopy(c)), list('bcabcabcab'))
650 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
651 self.assertEqual(take(10, pickle.loads(pickle.dumps(c, proto))),
652 list('bcabcabcab'))
653 next(c)
654 self.assertEqual(take(10, pickle.loads(pickle.dumps(c, proto))),
655 list('cabcabcabc'))
656 next(c)
657 next(c)
658 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
659 self.pickletest(proto, cycle('abc'))
660
661 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
662 # test with partial consumed input iterable
663 it = iter('abcde')
664 c = cycle(it)
665 _ = [next(c) for i in range(2)] # consume 2 of 5 inputs
666 p = pickle.dumps(c, proto)
667 d = pickle.loads(p) # rebuild the cycle object
668 self.assertEqual(take(20, d), list('cdeabcdeabcdeabcdeab'))
669
670 # test with completely consumed input iterable
671 it = iter('abcde')
672 c = cycle(it)
673 _ = [next(c) for i in range(7)] # consume 7 of 5 inputs
674 p = pickle.dumps(c, proto)
675 d = pickle.loads(p) # rebuild the cycle object
676 self.assertEqual(take(20, d), list('cdeabcdeabcdeabcdeab'))
677
678 def test_cycle_unpickle_compat(self):
679 testcases = [
680 b'citertools\ncycle\n(c__builtin__\niter\n((lI1\naI2\naI3\natRI1\nbtR((lI1\naI0\ntb.',
681 b'citertools\ncycle\n(c__builtin__\niter\n(](K\x01K\x02K\x03etRK\x01btR(]K\x01aK\x00tb.',
682 b'\x80\x02citertools\ncycle\nc__builtin__\niter\n](K\x01K\x02K\x03e\x85RK\x01b\x85R]K\x01aK\x00\x86b.',
683 b'\x80\x03citertools\ncycle\ncbuiltins\niter\n](K\x01K\x02K\x03e\x85RK\x01b\x85R]K\x01aK\x00\x86b.',
684 b'\x80\x04\x95=\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x8c\x05cycle\x93\x8c\x08builtins\x8c\x04iter\x93](K\x01K\x02K\x03e\x85RK\x01b\x85R]K\x01aK\x00\x86b.',
685
686 b'citertools\ncycle\n(c__builtin__\niter\n((lp0\nI1\naI2\naI3\natRI1\nbtR(g0\nI1\ntb.',
687 b'citertools\ncycle\n(c__builtin__\niter\n(]q\x00(K\x01K\x02K\x03etRK\x01btR(h\x00K\x01tb.',
688 b'\x80\x02citertools\ncycle\nc__builtin__\niter\n]q\x00(K\x01K\x02K\x03e\x85RK\x01b\x85Rh\x00K\x01\x86b.',
689 b'\x80\x03citertools\ncycle\ncbuiltins\niter\n]q\x00(K\x01K\x02K\x03e\x85RK\x01b\x85Rh\x00K\x01\x86b.',
690 b'\x80\x04\x95<\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x8c\x05cycle\x93\x8c\x08builtins\x8c\x04iter\x93]\x94(K\x01K\x02K\x03e\x85RK\x01b\x85Rh\x00K\x01\x86b.',
691
692 b'citertools\ncycle\n(c__builtin__\niter\n((lI1\naI2\naI3\natRI1\nbtR((lI1\naI00\ntb.',
693 b'citertools\ncycle\n(c__builtin__\niter\n(](K\x01K\x02K\x03etRK\x01btR(]K\x01aI00\ntb.',
694 b'\x80\x02citertools\ncycle\nc__builtin__\niter\n](K\x01K\x02K\x03e\x85RK\x01b\x85R]K\x01a\x89\x86b.',
695 b'\x80\x03citertools\ncycle\ncbuiltins\niter\n](K\x01K\x02K\x03e\x85RK\x01b\x85R]K\x01a\x89\x86b.',
696 b'\x80\x04\x95<\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x8c\x05cycle\x93\x8c\x08builtins\x8c\x04iter\x93](K\x01K\x02K\x03e\x85RK\x01b\x85R]K\x01a\x89\x86b.',
697
698 b'citertools\ncycle\n(c__builtin__\niter\n((lp0\nI1\naI2\naI3\natRI1\nbtR(g0\nI01\ntb.',
699 b'citertools\ncycle\n(c__builtin__\niter\n(]q\x00(K\x01K\x02K\x03etRK\x01btR(h\x00I01\ntb.',
700 b'\x80\x02citertools\ncycle\nc__builtin__\niter\n]q\x00(K\x01K\x02K\x03e\x85RK\x01b\x85Rh\x00\x88\x86b.',
701 b'\x80\x03citertools\ncycle\ncbuiltins\niter\n]q\x00(K\x01K\x02K\x03e\x85RK\x01b\x85Rh\x00\x88\x86b.',
702 b'\x80\x04\x95;\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x8c\x05cycle\x93\x8c\x08builtins\x8c\x04iter\x93]\x94(K\x01K\x02K\x03e\x85RK\x01b\x85Rh\x00\x88\x86b.',
703 ]
704 assert len(testcases) == 20
705 for t in testcases:
706 it = pickle.loads(t)
707 self.assertEqual(take(10, it), [2, 3, 1, 2, 3, 1, 2, 3, 1, 2])
708
709 @support.impl_detail("XXX cycle.__reduce__ and __setstate__ differ"
710 " on PyPy (but could be fixed if important)")
711 def test_cycle_setstate(self):
712 # Verify both modes for restoring state
713
714 # Mode 0 is efficient. It uses an incompletely consumed input
715 # iterator to build a cycle object and then passes in state with
716 # a list of previously consumed values. There is no data
717 # overlap between the two.
718 c = cycle('defg')
719 c.__setstate__((list('abc'), 0))
720 self.assertEqual(take(20, c), list('defgabcdefgabcdefgab'))
721
722 # Mode 1 is inefficient. It starts with a cycle object built
723 # from an iterator over the remaining elements in a partial
724 # cycle and then passes in state with all of the previously
725 # seen values (this overlaps values included in the iterator).
726 c = cycle('defg')
727 c.__setstate__((list('abcdefg'), 1))
728 self.assertEqual(take(20, c), list('defgabcdefgabcdefgab'))
729
730 # The first argument to setstate needs to be a tuple
731 with self.assertRaises(TypeError):
732 cycle('defg').__setstate__([list('abcdefg'), 0])
733
734 # The first argument in the setstate tuple must be a list
735 with self.assertRaises(TypeError):
736 c = cycle('defg')
737 c.__setstate__((tuple('defg'), 0))
738 take(20, c)
739
740 # The second argument in the setstate tuple must be an int
741 with self.assertRaises(TypeError):
742 cycle('defg').__setstate__((list('abcdefg'), 'x'))
743
744 self.assertRaises(TypeError, cycle('').__setstate__, ())
745 self.assertRaises(TypeError, cycle('').__setstate__, ([],))
746
747 def test_groupby(self):
748 # Check whether it accepts arguments correctly
749 self.assertEqual([], list(groupby([])))
750 self.assertEqual([], list(groupby([], key=id)))
751 self.assertRaises(TypeError, list, groupby('abc', []))
752 self.assertRaises(TypeError, groupby, None)
753 self.assertRaises(TypeError, groupby, 'abc', lambda x:x, 10)
754
755 # Check normal input
756 s = [(0, 10, 20), (0, 11,21), (0,12,21), (1,13,21), (1,14,22),
757 (2,15,22), (3,16,23), (3,17,23)]
758 dup = []
759 for k, g in groupby(s, lambda r:r[0]):
760 for elem in g:
761 self.assertEqual(k, elem[0])
762 dup.append(elem)
763 self.assertEqual(s, dup)
764
765 # Check normal pickled
766 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
767 dup = []
768 for k, g in pickle.loads(pickle.dumps(groupby(s, testR), proto)):
769 for elem in g:
770 self.assertEqual(k, elem[0])
771 dup.append(elem)
772 self.assertEqual(s, dup)
773
774 # Check nested case
775 dup = []
776 for k, g in groupby(s, testR):
777 for ik, ig in groupby(g, testR2):
778 for elem in ig:
779 self.assertEqual(k, elem[0])
780 self.assertEqual(ik, elem[2])
781 dup.append(elem)
782 self.assertEqual(s, dup)
783
784 # Check nested and pickled
785 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
786 dup = []
787 for k, g in pickle.loads(pickle.dumps(groupby(s, testR), proto)):
788 for ik, ig in pickle.loads(pickle.dumps(groupby(g, testR2), proto)):
789 for elem in ig:
790 self.assertEqual(k, elem[0])
791 self.assertEqual(ik, elem[2])
792 dup.append(elem)
793 self.assertEqual(s, dup)
794
795
796 # Check case where inner iterator is not used
797 keys = [k for k, g in groupby(s, testR)]
798 expectedkeys = set([r[0] for r in s])
799 self.assertEqual(set(keys), expectedkeys)
800 self.assertEqual(len(keys), len(expectedkeys))
801
802 # Check case where inner iterator is used after advancing the groupby
803 # iterator
804 s = list(zip('AABBBAAAA', range(9)))
805 it = groupby(s, testR)
806 _, g1 = next(it)
807 _, g2 = next(it)
808 _, g3 = next(it)
809 self.assertEqual(list(g1), [])
810 self.assertEqual(list(g2), [])
811 self.assertEqual(next(g3), ('A', 5))
812 list(it) # exhaust the groupby iterator
813 self.assertEqual(list(g3), [])
814
815 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
816 it = groupby(s, testR)
817 _, g = next(it)
818 next(it)
819 next(it)
820 self.assertEqual(list(pickle.loads(pickle.dumps(g, proto))), [])
821
822 # Exercise pipes and filters style
823 s = 'abracadabra'
824 # sort s | uniq
825 r = [k for k, g in groupby(sorted(s))]
826 self.assertEqual(r, ['a', 'b', 'c', 'd', 'r'])
827 # sort s | uniq -d
828 r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))]
829 self.assertEqual(r, ['a', 'b', 'r'])
830 # sort s | uniq -c
831 r = [(len(list(g)), k) for k, g in groupby(sorted(s))]
832 self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')])
833 # sort s | uniq -c | sort -rn | head -3
834 r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3]
835 self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')])
836
837 # iter.__next__ failure
838 class ExpectedError(Exception):
839 pass
840 def delayed_raise(n=0):
841 for i in range(n):
842 yield 'yo'
843 raise ExpectedError
844 def gulp(iterable, keyp=None, func=list):
845 return [func(g) for k, g in groupby(iterable, keyp)]
846
847 # iter.__next__ failure on outer object
848 self.assertRaises(ExpectedError, gulp, delayed_raise(0))
849 # iter.__next__ failure on inner object
850 self.assertRaises(ExpectedError, gulp, delayed_raise(1))
851
852 # __eq__ failure
853 class DummyCmp:
854 def __eq__(self, dst):
855 raise ExpectedError
856 s = [DummyCmp(), DummyCmp(), None]
857
858 # __eq__ failure on outer object
859 self.assertRaises(ExpectedError, gulp, s, func=id)
860 # __eq__ failure on inner object
861 self.assertRaises(ExpectedError, gulp, s)
862
863 # keyfunc failure
864 def keyfunc(obj):
865 if keyfunc.skip > 0:
866 keyfunc.skip -= 1
867 return obj
868 else:
869 raise ExpectedError
870
871 # keyfunc failure on outer object
872 keyfunc.skip = 0
873 self.assertRaises(ExpectedError, gulp, [None], keyfunc)
874 keyfunc.skip = 1
875 self.assertRaises(ExpectedError, gulp, [None, None], keyfunc)
876
877 def test_filter(self):
878 self.assertEqual(list(filter(isEven, range(6))), [0,2,4])
879 self.assertEqual(list(filter(None, [0,1,0,2,0])), [1,2])
880 self.assertEqual(list(filter(bool, [0,1,0,2,0])), [1,2])
881 self.assertEqual(take(4, filter(isEven, count())), [0,2,4,6])
882 self.assertRaises(TypeError, filter)
883 self.assertRaises(TypeError, filter, lambda x:x)
884 self.assertRaises(TypeError, filter, lambda x:x, range(6), 7)
885 self.assertRaises(TypeError, filter, isEven, 3)
886 self.assertRaises(TypeError, next, filter(range(6), range(6)))
887
888 # check copy, deepcopy, pickle
889 ans = [0,2,4]
890
891 c = filter(isEven, range(6))
892 self.assertEqual(list(copy.copy(c)), ans)
893 c = filter(isEven, range(6))
894 self.assertEqual(list(copy.deepcopy(c)), ans)
895 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
896 c = filter(isEven, range(6))
897 self.assertEqual(list(pickle.loads(pickle.dumps(c, proto))), ans)
898 next(c)
899 self.assertEqual(list(pickle.loads(pickle.dumps(c, proto))), ans[1:])
900 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
901 c = filter(isEven, range(6))
902 self.pickletest(proto, c)
903
904 def test_filterfalse(self):
905 self.assertEqual(list(filterfalse(isEven, range(6))), [1,3,5])
906 self.assertEqual(list(filterfalse(None, [0,1,0,2,0])), [0,0,0])
907 self.assertEqual(list(filterfalse(bool, [0,1,0,2,0])), [0,0,0])
908 self.assertEqual(take(4, filterfalse(isEven, count())), [1,3,5,7])
909 self.assertRaises(TypeError, filterfalse)
910 self.assertRaises(TypeError, filterfalse, lambda x:x)
911 self.assertRaises(TypeError, filterfalse, lambda x:x, range(6), 7)
912 self.assertRaises(TypeError, filterfalse, isEven, 3)
913 self.assertRaises(TypeError, next, filterfalse(range(6), range(6)))
914 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
915 self.pickletest(proto, filterfalse(isEven, range(6)))
916
917 def test_zip(self):
918 # XXX This is rather silly now that builtin zip() calls zip()...
919 ans = [(x,y) for x, y in zip('abc',count())]
920 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
921 self.assertEqual(list(zip('abc', range(6))), lzip('abc', range(6)))
922 self.assertEqual(list(zip('abcdef', range(3))), lzip('abcdef', range(3)))
923 self.assertEqual(take(3,zip('abcdef', count())), lzip('abcdef', range(3)))
924 self.assertEqual(list(zip('abcdef')), lzip('abcdef'))
925 self.assertEqual(list(zip()), lzip())
926 self.assertRaises(TypeError, zip, 3)
927 self.assertRaises(TypeError, zip, range(3), 3)
928 self.assertEqual([tuple(list(pair)) for pair in zip('abc', 'def')],
929 lzip('abc', 'def'))
930 self.assertEqual([pair for pair in zip('abc', 'def')],
931 lzip('abc', 'def'))
932
933 @support.impl_detail("tuple reuse is specific to CPython")
934 def test_zip_tuple_reuse(self):
935 ids = list(map(id, zip('abc', 'def')))
936 self.assertEqual(min(ids), max(ids))
937 ids = list(map(id, list(zip('abc', 'def'))))
938 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
939
940 # check copy, deepcopy, pickle
941 ans = [(x,y) for x, y in copy.copy(zip('abc',count()))]
942 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
943
944 ans = [(x,y) for x, y in copy.deepcopy(zip('abc',count()))]
945 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
946
947 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
948 ans = [(x,y) for x, y in pickle.loads(pickle.dumps(zip('abc',count()), proto))]
949 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
950
951 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
952 testIntermediate = zip('abc',count())
953 next(testIntermediate)
954 ans = [(x,y) for x, y in pickle.loads(pickle.dumps(testIntermediate, proto))]
955 self.assertEqual(ans, [('b', 1), ('c', 2)])
956
957 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
958 self.pickletest(proto, zip('abc', count()))
959
960 def test_ziplongest(self):
961 for args in [
962 ['abc', range(6)],
963 [range(6), 'abc'],
964 [range(1000), range(2000,2100), range(3000,3050)],
965 [range(1000), range(0), range(3000,3050), range(1200), range(1500)],
966 [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
967 ]:
968 target = [tuple([arg[i] if i < len(arg) else None for arg in args])
969 for i in range(max(map(len, args)))]
970 self.assertEqual(list(zip_longest(*args)), target)
971 self.assertEqual(list(zip_longest(*args, **{})), target)
972 target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X'
973 self.assertEqual(list(zip_longest(*args, **dict(fillvalue='X'))), target)
974
975 self.assertEqual(take(3,zip_longest('abcdef', count())), list(zip('abcdef', range(3)))) # take 3 from infinite input
976
977 self.assertEqual(list(zip_longest()), list(zip()))
978 self.assertEqual(list(zip_longest([])), list(zip([])))
979 self.assertEqual(list(zip_longest('abcdef')), list(zip('abcdef')))
980
981 self.assertEqual(list(zip_longest('abc', 'defg', **{})),
982 list(zip(list('abc')+[None], 'defg'))) # empty keyword dict
983 self.assertRaises(TypeError, zip_longest, 3)
984 self.assertRaises(TypeError, zip_longest, range(3), 3)
985
986 for stmt in [
987 "zip_longest('abc', fv=1)",
988 "zip_longest('abc', fillvalue=1, bogus_keyword=None)",
989 ]:
990 try:
991 eval(stmt, globals(), locals())
992 except TypeError:
993 pass
994 else:
995 self.fail('Did not raise Type in: ' + stmt)
996
997 self.assertEqual([tuple(list(pair)) for pair in zip_longest('abc', 'def')],
998 list(zip('abc', 'def')))
999 self.assertEqual([pair for pair in zip_longest('abc', 'def')],
1000 list(zip('abc', 'def')))
1001
1002 @support.impl_detail("tuple reuse is specific to CPython")
1003 def test_zip_longest_tuple_reuse(self):
1004 ids = list(map(id, zip_longest('abc', 'def')))
1005 self.assertEqual(min(ids), max(ids))
1006 ids = list(map(id, list(zip_longest('abc', 'def'))))
1007 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
1008
1009 def test_zip_longest_pickling(self):
1010 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1011 self.pickletest(proto, zip_longest("abc", "def"))
1012 self.pickletest(proto, zip_longest("abc", "defgh"))
1013 self.pickletest(proto, zip_longest("abc", "defgh", fillvalue=1))
1014 self.pickletest(proto, zip_longest("", "defgh"))
1015
1016 def test_zip_longest_bad_iterable(self):
1017 exception = TypeError()
1018
1019 class BadIterable:
1020 def __iter__(self):
1021 raise exception
1022
1023 with self.assertRaises(TypeError) as cm:
1024 zip_longest(BadIterable())
1025
1026 self.assertIs(cm.exception, exception)
1027
1028 def test_bug_7244(self):
1029
1030 class Repeater:
1031 # this class is similar to itertools.repeat
1032 def __init__(self, o, t, e):
1033 self.o = o
1034 self.t = int(t)
1035 self.e = e
1036 def __iter__(self): # its iterator is itself
1037 return self
1038 def __next__(self):
1039 if self.t > 0:
1040 self.t -= 1
1041 return self.o
1042 else:
1043 raise self.e
1044
1045 # Formerly this code in would fail in debug mode
1046 # with Undetected Error and Stop Iteration
1047 r1 = Repeater(1, 3, StopIteration)
1048 r2 = Repeater(2, 4, StopIteration)
1049 def run(r1, r2):
1050 result = []
1051 for i, j in zip_longest(r1, r2, fillvalue=0):
1052 with support.captured_output('stdout'):
1053 print((i, j))
1054 result.append((i, j))
1055 return result
1056 self.assertEqual(run(r1, r2), [(1,2), (1,2), (1,2), (0,2)])
1057
1058 # Formerly, the RuntimeError would be lost
1059 # and StopIteration would stop as expected
1060 r1 = Repeater(1, 3, RuntimeError)
1061 r2 = Repeater(2, 4, StopIteration)
1062 it = zip_longest(r1, r2, fillvalue=0)
1063 self.assertEqual(next(it), (1, 2))
1064 self.assertEqual(next(it), (1, 2))
1065 self.assertEqual(next(it), (1, 2))
1066 self.assertRaises(RuntimeError, next, it)
1067
1068 def test_pairwise(self):
1069 self.assertEqual(list(pairwise('')), [])
1070 self.assertEqual(list(pairwise('a')), [])
1071 self.assertEqual(list(pairwise('ab')),
1072 [('a', 'b')]),
1073 self.assertEqual(list(pairwise('abcde')),
1074 [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')])
1075 self.assertEqual(list(pairwise(range(10_000))),
1076 list(zip(range(10_000), range(1, 10_000))))
1077
1078 with self.assertRaises(TypeError):
1079 pairwise() # too few arguments
1080 with self.assertRaises(TypeError):
1081 pairwise('abc', 10) # too many arguments
1082 with self.assertRaises(TypeError):
1083 pairwise(iterable='abc') # keyword arguments
1084 with self.assertRaises(TypeError):
1085 pairwise(None) # non-iterable argument
1086
1087 def test_pairwise_reenter(self):
1088 def check(reenter_at, expected):
1089 class I:
1090 count = 0
1091 def __iter__(self):
1092 return self
1093 def __next__(self):
1094 self.count +=1
1095 if self.count in reenter_at:
1096 return next(it)
1097 return [self.count] # new object
1098
1099 it = pairwise(I())
1100 for item in expected:
1101 self.assertEqual(next(it), item)
1102
1103 check({1}, [
1104 (([2], [3]), [4]),
1105 ([4], [5]),
1106 ])
1107 check({2}, [
1108 ([1], ([1], [3])),
1109 (([1], [3]), [4]),
1110 ([4], [5]),
1111 ])
1112 check({3}, [
1113 ([1], [2]),
1114 ([2], ([2], [4])),
1115 (([2], [4]), [5]),
1116 ([5], [6]),
1117 ])
1118 check({1, 2}, [
1119 ((([3], [4]), [5]), [6]),
1120 ([6], [7]),
1121 ])
1122 check({1, 3}, [
1123 (([2], ([2], [4])), [5]),
1124 ([5], [6]),
1125 ])
1126 check({1, 4}, [
1127 (([2], [3]), (([2], [3]), [5])),
1128 ((([2], [3]), [5]), [6]),
1129 ([6], [7]),
1130 ])
1131 check({2, 3}, [
1132 ([1], ([1], ([1], [4]))),
1133 (([1], ([1], [4])), [5]),
1134 ([5], [6]),
1135 ])
1136
1137 def test_pairwise_reenter2(self):
1138 def check(maxcount, expected):
1139 class I:
1140 count = 0
1141 def __iter__(self):
1142 return self
1143 def __next__(self):
1144 if self.count >= maxcount:
1145 raise StopIteration
1146 self.count +=1
1147 if self.count == 1:
1148 return next(it, None)
1149 return [self.count] # new object
1150
1151 it = pairwise(I())
1152 self.assertEqual(list(it), expected)
1153
1154 check(1, [])
1155 check(2, [])
1156 check(3, [])
1157 check(4, [(([2], [3]), [4])])
1158
1159 def test_product(self):
1160 for args, result in [
1161 ([], [()]), # zero iterables
1162 (['ab'], [('a',), ('b',)]), # one iterable
1163 ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables
1164 ([range(0), range(2), range(3)], []), # first iterable with zero length
1165 ([range(2), range(0), range(3)], []), # middle iterable with zero length
1166 ([range(2), range(3), range(0)], []), # last iterable with zero length
1167 ]:
1168 self.assertEqual(list(product(*args)), result)
1169 for r in range(4):
1170 self.assertEqual(list(product(*(args*r))),
1171 list(product(*args, **dict(repeat=r))))
1172 self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
1173 self.assertRaises(TypeError, product, range(6), None)
1174
1175 def product1(*args, **kwds):
1176 pools = list(map(tuple, args)) * kwds.get('repeat', 1)
1177 n = len(pools)
1178 if n == 0:
1179 yield ()
1180 return
1181 if any(len(pool) == 0 for pool in pools):
1182 return
1183 indices = [0] * n
1184 yield tuple(pool[i] for pool, i in zip(pools, indices))
1185 while 1:
1186 for i in reversed(range(n)): # right to left
1187 if indices[i] == len(pools[i]) - 1:
1188 continue
1189 indices[i] += 1
1190 for j in range(i+1, n):
1191 indices[j] = 0
1192 yield tuple(pool[i] for pool, i in zip(pools, indices))
1193 break
1194 else:
1195 return
1196
1197 def product2(*args, **kwds):
1198 'Pure python version used in docs'
1199 pools = list(map(tuple, args)) * kwds.get('repeat', 1)
1200 result = [[]]
1201 for pool in pools:
1202 result = [x+[y] for x in result for y in pool]
1203 for prod in result:
1204 yield tuple(prod)
1205
1206 argtypes = ['', 'abc', '', range(0), range(4), dict(a=1, b=2, c=3),
1207 set('abcdefg'), range(11), tuple(range(13))]
1208 for i in range(100):
1209 args = [random.choice(argtypes) for j in range(random.randrange(5))]
1210 expected_len = prod(map(len, args))
1211 self.assertEqual(len(list(product(*args))), expected_len)
1212 self.assertEqual(list(product(*args)), list(product1(*args)))
1213 self.assertEqual(list(product(*args)), list(product2(*args)))
1214 args = map(iter, args)
1215 self.assertEqual(len(list(product(*args))), expected_len)
1216
1217 @support.bigaddrspacetest
1218 def test_product_overflow(self):
1219 with self.assertRaises((OverflowError, MemoryError)):
1220 product(*(['ab']*2**5), repeat=2**25)
1221
1222 @support.impl_detail("tuple reuse is specific to CPython")
1223 def test_product_tuple_reuse(self):
1224 self.assertEqual(len(set(map(id, product('abc', 'def')))), 1)
1225 self.assertNotEqual(len(set(map(id, list(product('abc', 'def'))))), 1)
1226
1227 def test_product_pickling(self):
1228 # check copy, deepcopy, pickle
1229 for args, result in [
1230 ([], [()]), # zero iterables
1231 (['ab'], [('a',), ('b',)]), # one iterable
1232 ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables
1233 ([range(0), range(2), range(3)], []), # first iterable with zero length
1234 ([range(2), range(0), range(3)], []), # middle iterable with zero length
1235 ([range(2), range(3), range(0)], []), # last iterable with zero length
1236 ]:
1237 self.assertEqual(list(copy.copy(product(*args))), result)
1238 self.assertEqual(list(copy.deepcopy(product(*args))), result)
1239 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1240 self.pickletest(proto, product(*args))
1241
1242 def test_product_issue_25021(self):
1243 # test that indices are properly clamped to the length of the tuples
1244 p = product((1, 2),(3,))
1245 p.__setstate__((0, 0x1000)) # will access tuple element 1 if not clamped
1246 self.assertEqual(next(p), (2, 3))
1247 # test that empty tuple in the list will result in an immediate StopIteration
1248 p = product((1, 2), (), (3,))
1249 p.__setstate__((0, 0, 0x1000)) # will access tuple element 1 if not clamped
1250 self.assertRaises(StopIteration, next, p)
1251
1252 def test_repeat(self):
1253 self.assertEqual(list(repeat(object='a', times=3)), ['a', 'a', 'a'])
1254 self.assertEqual(lzip(range(3),repeat('a')),
1255 [(0, 'a'), (1, 'a'), (2, 'a')])
1256 self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
1257 self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
1258 self.assertEqual(list(repeat('a', 0)), [])
1259 self.assertEqual(list(repeat('a', -3)), [])
1260 self.assertRaises(TypeError, repeat)
1261 self.assertRaises(TypeError, repeat, None, 3, 4)
1262 self.assertRaises(TypeError, repeat, None, 'a')
1263 r = repeat(1+0j)
1264 self.assertEqual(repr(r), 'repeat((1+0j))')
1265 r = repeat(1+0j, 5)
1266 self.assertEqual(repr(r), 'repeat((1+0j), 5)')
1267 list(r)
1268 self.assertEqual(repr(r), 'repeat((1+0j), 0)')
1269
1270 # check copy, deepcopy, pickle
1271 c = repeat(object='a', times=10)
1272 self.assertEqual(next(c), 'a')
1273 self.assertEqual(take(2, copy.copy(c)), list('a' * 2))
1274 self.assertEqual(take(2, copy.deepcopy(c)), list('a' * 2))
1275 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1276 self.pickletest(proto, repeat(object='a', times=10))
1277
1278 def test_repeat_with_negative_times(self):
1279 self.assertEqual(repr(repeat('a', -1)), "repeat('a', 0)")
1280 self.assertEqual(repr(repeat('a', -2)), "repeat('a', 0)")
1281 self.assertEqual(repr(repeat('a', times=-1)), "repeat('a', 0)")
1282 self.assertEqual(repr(repeat('a', times=-2)), "repeat('a', 0)")
1283
1284 def test_map(self):
1285 self.assertEqual(list(map(operator.pow, range(3), range(1,7))),
1286 [0**1, 1**2, 2**3])
1287 self.assertEqual(list(map(tupleize, 'abc', range(5))),
1288 [('a',0),('b',1),('c',2)])
1289 self.assertEqual(list(map(tupleize, 'abc', count())),
1290 [('a',0),('b',1),('c',2)])
1291 self.assertEqual(take(2,map(tupleize, 'abc', count())),
1292 [('a',0),('b',1)])
1293 self.assertEqual(list(map(operator.pow, [])), [])
1294 self.assertRaises(TypeError, map)
1295 self.assertRaises(TypeError, list, map(None, range(3), range(3)))
1296 self.assertRaises(TypeError, map, operator.neg)
1297 self.assertRaises(TypeError, next, map(10, range(5)))
1298 self.assertRaises(ValueError, next, map(errfunc, [4], [5]))
1299 self.assertRaises(TypeError, next, map(onearg, [4], [5]))
1300
1301 # check copy, deepcopy, pickle
1302 ans = [('a',0),('b',1),('c',2)]
1303
1304 c = map(tupleize, 'abc', count())
1305 self.assertEqual(list(copy.copy(c)), ans)
1306
1307 c = map(tupleize, 'abc', count())
1308 self.assertEqual(list(copy.deepcopy(c)), ans)
1309
1310 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1311 c = map(tupleize, 'abc', count())
1312 self.pickletest(proto, c)
1313
1314 def test_starmap(self):
1315 self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
1316 [0**1, 1**2, 2**3])
1317 self.assertEqual(take(3, starmap(operator.pow, zip(count(), count(1)))),
1318 [0**1, 1**2, 2**3])
1319 self.assertEqual(list(starmap(operator.pow, [])), [])
1320 self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5])
1321 self.assertRaises(TypeError, list, starmap(operator.pow, [None]))
1322 self.assertRaises(TypeError, starmap)
1323 self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
1324 self.assertRaises(TypeError, next, starmap(10, [(4,5)]))
1325 self.assertRaises(ValueError, next, starmap(errfunc, [(4,5)]))
1326 self.assertRaises(TypeError, next, starmap(onearg, [(4,5)]))
1327
1328 # check copy, deepcopy, pickle
1329 ans = [0**1, 1**2, 2**3]
1330
1331 c = starmap(operator.pow, zip(range(3), range(1,7)))
1332 self.assertEqual(list(copy.copy(c)), ans)
1333
1334 c = starmap(operator.pow, zip(range(3), range(1,7)))
1335 self.assertEqual(list(copy.deepcopy(c)), ans)
1336
1337 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1338 c = starmap(operator.pow, zip(range(3), range(1,7)))
1339 self.pickletest(proto, c)
1340
1341 def test_islice(self):
1342 for args in [ # islice(args) should agree with range(args)
1343 (10, 20, 3),
1344 (10, 3, 20),
1345 (10, 20),
1346 (10, 10),
1347 (10, 3),
1348 (20,)
1349 ]:
1350 self.assertEqual(list(islice(range(100), *args)),
1351 list(range(*args)))
1352
1353 for args, tgtargs in [ # Stop when seqn is exhausted
1354 ((10, 110, 3), ((10, 100, 3))),
1355 ((10, 110), ((10, 100))),
1356 ((110,), (100,))
1357 ]:
1358 self.assertEqual(list(islice(range(100), *args)),
1359 list(range(*tgtargs)))
1360
1361 # Test stop=None
1362 self.assertEqual(list(islice(range(10), None)), list(range(10)))
1363 self.assertEqual(list(islice(range(10), None, None)), list(range(10)))
1364 self.assertEqual(list(islice(range(10), None, None, None)), list(range(10)))
1365 self.assertEqual(list(islice(range(10), 2, None)), list(range(2, 10)))
1366 self.assertEqual(list(islice(range(10), 1, None, 2)), list(range(1, 10, 2)))
1367
1368 # Test number of items consumed SF #1171417
1369 it = iter(range(10))
1370 self.assertEqual(list(islice(it, 3)), list(range(3)))
1371 self.assertEqual(list(it), list(range(3, 10)))
1372
1373 it = iter(range(10))
1374 self.assertEqual(list(islice(it, 3, 3)), [])
1375 self.assertEqual(list(it), list(range(3, 10)))
1376
1377 # Test invalid arguments
1378 ra = range(10)
1379 self.assertRaises(TypeError, islice, ra)
1380 self.assertRaises(TypeError, islice, ra, 1, 2, 3, 4)
1381 self.assertRaises(ValueError, islice, ra, -5, 10, 1)
1382 self.assertRaises(ValueError, islice, ra, 1, -5, -1)
1383 self.assertRaises(ValueError, islice, ra, 1, 10, -1)
1384 self.assertRaises(ValueError, islice, ra, 1, 10, 0)
1385 self.assertRaises(ValueError, islice, ra, 'a')
1386 self.assertRaises(ValueError, islice, ra, 'a', 1)
1387 self.assertRaises(ValueError, islice, ra, 1, 'a')
1388 self.assertRaises(ValueError, islice, ra, 'a', 1, 1)
1389 self.assertRaises(ValueError, islice, ra, 1, 'a', 1)
1390 self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
1391
1392 # Issue #10323: Less islice in a predictable state
1393 c = count()
1394 self.assertEqual(list(islice(c, 1, 3, 50)), [1])
1395 self.assertEqual(next(c), 3)
1396
1397 # check copy, deepcopy, pickle
1398 for args in [ # islice(args) should agree with range(args)
1399 (10, 20, 3),
1400 (10, 3, 20),
1401 (10, 20),
1402 (10, 3),
1403 (20,)
1404 ]:
1405 self.assertEqual(list(copy.copy(islice(range(100), *args))),
1406 list(range(*args)))
1407 self.assertEqual(list(copy.deepcopy(islice(range(100), *args))),
1408 list(range(*args)))
1409 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1410 self.pickletest(proto, islice(range(100), *args))
1411
1412 # Issue #21321: check source iterator is not referenced
1413 # from islice() after the latter has been exhausted
1414 it = (x for x in (1, 2))
1415 wr = weakref.ref(it)
1416 it = islice(it, 1)
1417 self.assertIsNotNone(wr())
1418 list(it) # exhaust the iterator
1419 support.gc_collect()
1420 self.assertIsNone(wr())
1421
1422 # Issue #30537: islice can accept integer-like objects as
1423 # arguments
1424 class IntLike(object):
1425 def __init__(self, val):
1426 self.val = val
1427 def __index__(self):
1428 return self.val
1429 self.assertEqual(list(islice(range(100), IntLike(10))), list(range(10)))
1430 self.assertEqual(list(islice(range(100), IntLike(10), IntLike(50))),
1431 list(range(10, 50)))
1432 self.assertEqual(list(islice(range(100), IntLike(10), IntLike(50), IntLike(5))),
1433 list(range(10,50,5)))
1434
1435 def test_takewhile(self):
1436 data = [1, 3, 5, 20, 2, 4, 6, 8]
1437 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
1438 self.assertEqual(list(takewhile(underten, [])), [])
1439 self.assertRaises(TypeError, takewhile)
1440 self.assertRaises(TypeError, takewhile, operator.pow)
1441 self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
1442 self.assertRaises(TypeError, next, takewhile(10, [(4,5)]))
1443 self.assertRaises(ValueError, next, takewhile(errfunc, [(4,5)]))
1444 t = takewhile(bool, [1, 1, 1, 0, 0, 0])
1445 self.assertEqual(list(t), [1, 1, 1])
1446 self.assertRaises(StopIteration, next, t)
1447
1448 # check copy, deepcopy, pickle
1449 self.assertEqual(list(copy.copy(takewhile(underten, data))), [1, 3, 5])
1450 self.assertEqual(list(copy.deepcopy(takewhile(underten, data))),
1451 [1, 3, 5])
1452 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1453 self.pickletest(proto, takewhile(underten, data))
1454
1455 def test_dropwhile(self):
1456 data = [1, 3, 5, 20, 2, 4, 6, 8]
1457 self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
1458 self.assertEqual(list(dropwhile(underten, [])), [])
1459 self.assertRaises(TypeError, dropwhile)
1460 self.assertRaises(TypeError, dropwhile, operator.pow)
1461 self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
1462 self.assertRaises(TypeError, next, dropwhile(10, [(4,5)]))
1463 self.assertRaises(ValueError, next, dropwhile(errfunc, [(4,5)]))
1464
1465 # check copy, deepcopy, pickle
1466 self.assertEqual(list(copy.copy(dropwhile(underten, data))), [20, 2, 4, 6, 8])
1467 self.assertEqual(list(copy.deepcopy(dropwhile(underten, data))),
1468 [20, 2, 4, 6, 8])
1469 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1470 self.pickletest(proto, dropwhile(underten, data))
1471
1472 def test_tee(self):
1473 n = 200
1474
1475 a, b = tee([]) # test empty iterator
1476 self.assertEqual(list(a), [])
1477 self.assertEqual(list(b), [])
1478
1479 a, b = tee(irange(n)) # test 100% interleaved
1480 self.assertEqual(lzip(a,b), lzip(range(n), range(n)))
1481
1482 a, b = tee(irange(n)) # test 0% interleaved
1483 self.assertEqual(list(a), list(range(n)))
1484 self.assertEqual(list(b), list(range(n)))
1485
1486 a, b = tee(irange(n)) # test dealloc of leading iterator
1487 for i in range(100):
1488 self.assertEqual(next(a), i)
1489 del a
1490 self.assertEqual(list(b), list(range(n)))
1491
1492 a, b = tee(irange(n)) # test dealloc of trailing iterator
1493 for i in range(100):
1494 self.assertEqual(next(a), i)
1495 del b
1496 self.assertEqual(list(a), list(range(100, n)))
1497
1498 for j in range(5): # test randomly interleaved
1499 order = [0]*n + [1]*n
1500 random.shuffle(order)
1501 lists = ([], [])
1502 its = tee(irange(n))
1503 for i in order:
1504 value = next(its[i])
1505 lists[i].append(value)
1506 self.assertEqual(lists[0], list(range(n)))
1507 self.assertEqual(lists[1], list(range(n)))
1508
1509 # test argument format checking
1510 self.assertRaises(TypeError, tee)
1511 self.assertRaises(TypeError, tee, 3)
1512 self.assertRaises(TypeError, tee, [1,2], 'x')
1513 self.assertRaises(TypeError, tee, [1,2], 3, 'x')
1514
1515 # tee object should be instantiable
1516 a, b = tee('abc')
1517 c = type(a)('def')
1518 self.assertEqual(list(c), list('def'))
1519
1520 # test long-lagged and multi-way split
1521 a, b, c = tee(range(2000), 3)
1522 for i in range(100):
1523 self.assertEqual(next(a), i)
1524 self.assertEqual(list(b), list(range(2000)))
1525 self.assertEqual([next(c), next(c)], list(range(2)))
1526 self.assertEqual(list(a), list(range(100,2000)))
1527 self.assertEqual(list(c), list(range(2,2000)))
1528
1529 # test values of n
1530 self.assertRaises(TypeError, tee, 'abc', 'invalid')
1531 self.assertRaises(ValueError, tee, [], -1)
1532 for n in range(5):
1533 result = tee('abc', n)
1534 self.assertEqual(type(result), tuple)
1535 self.assertEqual(len(result), n)
1536 self.assertEqual([list(x) for x in result], [list('abc')]*n)
1537
1538 # tee pass-through to copyable iterator
1539 a, b = tee('abc')
1540 c, d = tee(a)
1541 self.assertTrue(a is c)
1542
1543 # test tee_new
1544 t1, t2 = tee('abc')
1545 tnew = type(t1)
1546 self.assertRaises(TypeError, tnew)
1547 self.assertRaises(TypeError, tnew, 10)
1548 t3 = tnew(t1)
1549 self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc'))
1550
1551 # test that tee objects are weak referencable
1552 a, b = tee(range(10))
1553 p = weakref.proxy(a)
1554 self.assertEqual(getattr(p, '__class__'), type(b))
1555 del a
1556 support.gc_collect() # For PyPy or other GCs.
1557 self.assertRaises(ReferenceError, getattr, p, '__class__')
1558
1559 ans = list('abc')
1560 long_ans = list(range(10000))
1561
1562 # check copy
1563 a, b = tee('abc')
1564 self.assertEqual(list(copy.copy(a)), ans)
1565 self.assertEqual(list(copy.copy(b)), ans)
1566 a, b = tee(list(range(10000)))
1567 self.assertEqual(list(copy.copy(a)), long_ans)
1568 self.assertEqual(list(copy.copy(b)), long_ans)
1569
1570 # check partially consumed copy
1571 a, b = tee('abc')
1572 take(2, a)
1573 take(1, b)
1574 self.assertEqual(list(copy.copy(a)), ans[2:])
1575 self.assertEqual(list(copy.copy(b)), ans[1:])
1576 self.assertEqual(list(a), ans[2:])
1577 self.assertEqual(list(b), ans[1:])
1578 a, b = tee(range(10000))
1579 take(100, a)
1580 take(60, b)
1581 self.assertEqual(list(copy.copy(a)), long_ans[100:])
1582 self.assertEqual(list(copy.copy(b)), long_ans[60:])
1583 self.assertEqual(list(a), long_ans[100:])
1584 self.assertEqual(list(b), long_ans[60:])
1585
1586 # check deepcopy
1587 a, b = tee('abc')
1588 self.assertEqual(list(copy.deepcopy(a)), ans)
1589 self.assertEqual(list(copy.deepcopy(b)), ans)
1590 self.assertEqual(list(a), ans)
1591 self.assertEqual(list(b), ans)
1592 a, b = tee(range(10000))
1593 self.assertEqual(list(copy.deepcopy(a)), long_ans)
1594 self.assertEqual(list(copy.deepcopy(b)), long_ans)
1595 self.assertEqual(list(a), long_ans)
1596 self.assertEqual(list(b), long_ans)
1597
1598 # check partially consumed deepcopy
1599 a, b = tee('abc')
1600 take(2, a)
1601 take(1, b)
1602 self.assertEqual(list(copy.deepcopy(a)), ans[2:])
1603 self.assertEqual(list(copy.deepcopy(b)), ans[1:])
1604 self.assertEqual(list(a), ans[2:])
1605 self.assertEqual(list(b), ans[1:])
1606 a, b = tee(range(10000))
1607 take(100, a)
1608 take(60, b)
1609 self.assertEqual(list(copy.deepcopy(a)), long_ans[100:])
1610 self.assertEqual(list(copy.deepcopy(b)), long_ans[60:])
1611 self.assertEqual(list(a), long_ans[100:])
1612 self.assertEqual(list(b), long_ans[60:])
1613
1614 # check pickle
1615 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1616 self.pickletest(proto, iter(tee('abc')))
1617 a, b = tee('abc')
1618 self.pickletest(proto, a, compare=ans)
1619 self.pickletest(proto, b, compare=ans)
1620
1621 # Issue 13454: Crash when deleting backward iterator from tee()
1622 def test_tee_del_backward(self):
1623 forward, backward = tee(repeat(None, 20000000))
1624 try:
1625 any(forward) # exhaust the iterator
1626 del backward
1627 except:
1628 del forward, backward
1629 raise
1630
1631 def test_tee_reenter(self):
1632 class I:
1633 first = True
1634 def __iter__(self):
1635 return self
1636 def __next__(self):
1637 first = self.first
1638 self.first = False
1639 if first:
1640 return next(b)
1641
1642 a, b = tee(I())
1643 with self.assertRaisesRegex(RuntimeError, "tee"):
1644 next(a)
1645
1646 @threading_helper.requires_working_threading()
1647 def test_tee_concurrent(self):
1648 start = threading.Event()
1649 finish = threading.Event()
1650 class I:
1651 def __iter__(self):
1652 return self
1653 def __next__(self):
1654 start.set()
1655 finish.wait()
1656
1657 a, b = tee(I())
1658 thread = threading.Thread(target=next, args=[a])
1659 thread.start()
1660 try:
1661 start.wait()
1662 with self.assertRaisesRegex(RuntimeError, "tee"):
1663 next(b)
1664 finally:
1665 finish.set()
1666 thread.join()
1667
1668 def test_StopIteration(self):
1669 self.assertRaises(StopIteration, next, zip())
1670
1671 for f in (chain, cycle, zip, groupby):
1672 self.assertRaises(StopIteration, next, f([]))
1673 self.assertRaises(StopIteration, next, f(StopNow()))
1674
1675 self.assertRaises(StopIteration, next, islice([], None))
1676 self.assertRaises(StopIteration, next, islice(StopNow(), None))
1677
1678 p, q = tee([])
1679 self.assertRaises(StopIteration, next, p)
1680 self.assertRaises(StopIteration, next, q)
1681 p, q = tee(StopNow())
1682 self.assertRaises(StopIteration, next, p)
1683 self.assertRaises(StopIteration, next, q)
1684
1685 self.assertRaises(StopIteration, next, repeat(None, 0))
1686
1687 for f in (filter, filterfalse, map, takewhile, dropwhile, starmap):
1688 self.assertRaises(StopIteration, next, f(lambda x:x, []))
1689 self.assertRaises(StopIteration, next, f(lambda x:x, StopNow()))
1690
1691 @support.cpython_only
1692 def test_combinations_result_gc(self):
1693 # bpo-42536: combinations's tuple-reuse speed trick breaks the GC's
1694 # assumptions about what can be untracked. Make sure we re-track result
1695 # tuples whenever we reuse them.
1696 it = combinations([None, []], 1)
1697 next(it)
1698 gc.collect()
1699 # That GC collection probably untracked the recycled internal result
1700 # tuple, which has the value (None,). Make sure it's re-tracked when
1701 # it's mutated and returned from __next__:
1702 self.assertTrue(gc.is_tracked(next(it)))
1703
1704 @support.cpython_only
1705 def test_combinations_with_replacement_result_gc(self):
1706 # Ditto for combinations_with_replacement.
1707 it = combinations_with_replacement([None, []], 1)
1708 next(it)
1709 gc.collect()
1710 self.assertTrue(gc.is_tracked(next(it)))
1711
1712 @support.cpython_only
1713 def test_permutations_result_gc(self):
1714 # Ditto for permutations.
1715 it = permutations([None, []], 1)
1716 next(it)
1717 gc.collect()
1718 self.assertTrue(gc.is_tracked(next(it)))
1719
1720 @support.cpython_only
1721 def test_product_result_gc(self):
1722 # Ditto for product.
1723 it = product([None, []])
1724 next(it)
1725 gc.collect()
1726 self.assertTrue(gc.is_tracked(next(it)))
1727
1728 @support.cpython_only
1729 def test_zip_longest_result_gc(self):
1730 # Ditto for zip_longest.
1731 it = zip_longest([[]])
1732 gc.collect()
1733 self.assertTrue(gc.is_tracked(next(it)))
1734
1735
1736 class TestExamples(unittest.TestCase):
1737
1738 def test_accumulate(self):
1739 self.assertEqual(list(accumulate([1,2,3,4,5])), [1, 3, 6, 10, 15])
1740
1741 def test_accumulate_reducible(self):
1742 # check copy, deepcopy, pickle
1743 data = [1, 2, 3, 4, 5]
1744 accumulated = [1, 3, 6, 10, 15]
1745
1746 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1747 it = accumulate(data)
1748 self.assertEqual(list(pickle.loads(pickle.dumps(it, proto))), accumulated[:])
1749 self.assertEqual(next(it), 1)
1750 self.assertEqual(list(pickle.loads(pickle.dumps(it, proto))), accumulated[1:])
1751 it = accumulate(data)
1752 self.assertEqual(next(it), 1)
1753 self.assertEqual(list(copy.deepcopy(it)), accumulated[1:])
1754 self.assertEqual(list(copy.copy(it)), accumulated[1:])
1755
1756 def test_accumulate_reducible_none(self):
1757 # Issue #25718: total is None
1758 it = accumulate([None, None, None], operator.is_)
1759 self.assertEqual(next(it), None)
1760 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1761 it_copy = pickle.loads(pickle.dumps(it, proto))
1762 self.assertEqual(list(it_copy), [True, False])
1763 self.assertEqual(list(copy.deepcopy(it)), [True, False])
1764 self.assertEqual(list(copy.copy(it)), [True, False])
1765
1766 def test_chain(self):
1767 self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF')
1768
1769 def test_chain_from_iterable(self):
1770 self.assertEqual(''.join(chain.from_iterable(['ABC', 'DEF'])), 'ABCDEF')
1771
1772 def test_combinations(self):
1773 self.assertEqual(list(combinations('ABCD', 2)),
1774 [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
1775 self.assertEqual(list(combinations(range(4), 3)),
1776 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
1777
1778 def test_combinations_with_replacement(self):
1779 self.assertEqual(list(combinations_with_replacement('ABC', 2)),
1780 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
1781
1782 def test_compress(self):
1783 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
1784
1785 def test_count(self):
1786 self.assertEqual(list(islice(count(10), 5)), [10, 11, 12, 13, 14])
1787
1788 def test_cycle(self):
1789 self.assertEqual(list(islice(cycle('ABCD'), 12)), list('ABCDABCDABCD'))
1790
1791 def test_dropwhile(self):
1792 self.assertEqual(list(dropwhile(lambda x: x<5, [1,4,6,4,1])), [6,4,1])
1793
1794 def test_groupby(self):
1795 self.assertEqual([k for k, g in groupby('AAAABBBCCDAABBB')],
1796 list('ABCDAB'))
1797 self.assertEqual([(list(g)) for k, g in groupby('AAAABBBCCD')],
1798 [list('AAAA'), list('BBB'), list('CC'), list('D')])
1799
1800 def test_filter(self):
1801 self.assertEqual(list(filter(lambda x: x%2, range(10))), [1,3,5,7,9])
1802
1803 def test_filterfalse(self):
1804 self.assertEqual(list(filterfalse(lambda x: x%2, range(10))), [0,2,4,6,8])
1805
1806 def test_map(self):
1807 self.assertEqual(list(map(pow, (2,3,10), (5,2,3))), [32, 9, 1000])
1808
1809 def test_islice(self):
1810 self.assertEqual(list(islice('ABCDEFG', 2)), list('AB'))
1811 self.assertEqual(list(islice('ABCDEFG', 2, 4)), list('CD'))
1812 self.assertEqual(list(islice('ABCDEFG', 2, None)), list('CDEFG'))
1813 self.assertEqual(list(islice('ABCDEFG', 0, None, 2)), list('ACEG'))
1814
1815 def test_zip(self):
1816 self.assertEqual(list(zip('ABCD', 'xy')), [('A', 'x'), ('B', 'y')])
1817
1818 def test_zip_longest(self):
1819 self.assertEqual(list(zip_longest('ABCD', 'xy', fillvalue='-')),
1820 [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')])
1821
1822 def test_permutations(self):
1823 self.assertEqual(list(permutations('ABCD', 2)),
1824 list(map(tuple, 'AB AC AD BA BC BD CA CB CD DA DB DC'.split())))
1825 self.assertEqual(list(permutations(range(3))),
1826 [(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0)])
1827
1828 def test_product(self):
1829 self.assertEqual(list(product('ABCD', 'xy')),
1830 list(map(tuple, 'Ax Ay Bx By Cx Cy Dx Dy'.split())))
1831 self.assertEqual(list(product(range(2), repeat=3)),
1832 [(0,0,0), (0,0,1), (0,1,0), (0,1,1),
1833 (1,0,0), (1,0,1), (1,1,0), (1,1,1)])
1834
1835 def test_repeat(self):
1836 self.assertEqual(list(repeat(10, 3)), [10, 10, 10])
1837
1838 def test_stapmap(self):
1839 self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])),
1840 [32, 9, 1000])
1841
1842 def test_takewhile(self):
1843 self.assertEqual(list(takewhile(lambda x: x<5, [1,4,6,4,1])), [1,4])
1844
1845
1846 class TestPurePythonRoughEquivalents(unittest.TestCase):
1847
1848 @staticmethod
1849 def islice(iterable, *args):
1850 s = slice(*args)
1851 start, stop, step = s.start or 0, s.stop or sys.maxsize, s.step or 1
1852 it = iter(range(start, stop, step))
1853 try:
1854 nexti = next(it)
1855 except StopIteration:
1856 # Consume *iterable* up to the *start* position.
1857 for i, element in zip(range(start), iterable):
1858 pass
1859 return
1860 try:
1861 for i, element in enumerate(iterable):
1862 if i == nexti:
1863 yield element
1864 nexti = next(it)
1865 except StopIteration:
1866 # Consume to *stop*.
1867 for i, element in zip(range(i + 1, stop), iterable):
1868 pass
1869
1870 def test_islice_recipe(self):
1871 self.assertEqual(list(self.islice('ABCDEFG', 2)), list('AB'))
1872 self.assertEqual(list(self.islice('ABCDEFG', 2, 4)), list('CD'))
1873 self.assertEqual(list(self.islice('ABCDEFG', 2, None)), list('CDEFG'))
1874 self.assertEqual(list(self.islice('ABCDEFG', 0, None, 2)), list('ACEG'))
1875 # Test items consumed.
1876 it = iter(range(10))
1877 self.assertEqual(list(self.islice(it, 3)), list(range(3)))
1878 self.assertEqual(list(it), list(range(3, 10)))
1879 it = iter(range(10))
1880 self.assertEqual(list(self.islice(it, 3, 3)), [])
1881 self.assertEqual(list(it), list(range(3, 10)))
1882 # Test that slice finishes in predictable state.
1883 c = count()
1884 self.assertEqual(list(self.islice(c, 1, 3, 50)), [1])
1885 self.assertEqual(next(c), 3)
1886
1887
1888 class TestGC(unittest.TestCase):
1889
1890 def makecycle(self, iterator, container):
1891 container.append(iterator)
1892 next(iterator)
1893 del container, iterator
1894
1895 def test_accumulate(self):
1896 a = []
1897 self.makecycle(accumulate([1,2,a,3]), a)
1898
1899 def test_chain(self):
1900 a = []
1901 self.makecycle(chain(a), a)
1902
1903 def test_chain_from_iterable(self):
1904 a = []
1905 self.makecycle(chain.from_iterable([a]), a)
1906
1907 def test_combinations(self):
1908 a = []
1909 self.makecycle(combinations([1,2,a,3], 3), a)
1910
1911 def test_combinations_with_replacement(self):
1912 a = []
1913 self.makecycle(combinations_with_replacement([1,2,a,3], 3), a)
1914
1915 def test_compress(self):
1916 a = []
1917 self.makecycle(compress('ABCDEF', [1,0,1,0,1,0]), a)
1918
1919 def test_count(self):
1920 a = []
1921 Int = type('Int', (int,), dict(x=a))
1922 self.makecycle(count(Int(0), Int(1)), a)
1923
1924 def test_cycle(self):
1925 a = []
1926 self.makecycle(cycle([a]*2), a)
1927
1928 def test_dropwhile(self):
1929 a = []
1930 self.makecycle(dropwhile(bool, [0, a, a]), a)
1931
1932 def test_groupby(self):
1933 a = []
1934 self.makecycle(groupby([a]*2, lambda x:x), a)
1935
1936 def test_issue2246(self):
1937 # Issue 2246 -- the _grouper iterator was not included in GC
1938 n = 10
1939 keyfunc = lambda x: x
1940 for i, j in groupby(range(n), key=keyfunc):
1941 keyfunc.__dict__.setdefault('x',[]).append(j)
1942
1943 def test_filter(self):
1944 a = []
1945 self.makecycle(filter(lambda x:True, [a]*2), a)
1946
1947 def test_filterfalse(self):
1948 a = []
1949 self.makecycle(filterfalse(lambda x:False, a), a)
1950
1951 def test_zip(self):
1952 a = []
1953 self.makecycle(zip([a]*2, [a]*3), a)
1954
1955 def test_zip_longest(self):
1956 a = []
1957 self.makecycle(zip_longest([a]*2, [a]*3), a)
1958 b = [a, None]
1959 self.makecycle(zip_longest([a]*2, [a]*3, fillvalue=b), a)
1960
1961 def test_map(self):
1962 a = []
1963 self.makecycle(map(lambda x:x, [a]*2), a)
1964
1965 def test_islice(self):
1966 a = []
1967 self.makecycle(islice([a]*2, None), a)
1968
1969 def test_pairwise(self):
1970 a = []
1971 self.makecycle(pairwise([a]*5), a)
1972
1973 def test_permutations(self):
1974 a = []
1975 self.makecycle(permutations([1,2,a,3], 3), a)
1976
1977 def test_product(self):
1978 a = []
1979 self.makecycle(product([1,2,a,3], repeat=3), a)
1980
1981 def test_repeat(self):
1982 a = []
1983 self.makecycle(repeat(a), a)
1984
1985 def test_starmap(self):
1986 a = []
1987 self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)
1988
1989 def test_takewhile(self):
1990 a = []
1991 self.makecycle(takewhile(bool, [1, 0, a, a]), a)
1992
1993 def R(seqn):
1994 'Regular generator'
1995 for i in seqn:
1996 yield i
1997
1998 class G:
1999 'Sequence using __getitem__'
2000 def __init__(self, seqn):
2001 self.seqn = seqn
2002 def __getitem__(self, i):
2003 return self.seqn[i]
2004
2005 class I:
2006 'Sequence using iterator protocol'
2007 def __init__(self, seqn):
2008 self.seqn = seqn
2009 self.i = 0
2010 def __iter__(self):
2011 return self
2012 def __next__(self):
2013 if self.i >= len(self.seqn): raise StopIteration
2014 v = self.seqn[self.i]
2015 self.i += 1
2016 return v
2017
2018 class Ig:
2019 'Sequence using iterator protocol defined with a generator'
2020 def __init__(self, seqn):
2021 self.seqn = seqn
2022 self.i = 0
2023 def __iter__(self):
2024 for val in self.seqn:
2025 yield val
2026
2027 class X:
2028 'Missing __getitem__ and __iter__'
2029 def __init__(self, seqn):
2030 self.seqn = seqn
2031 self.i = 0
2032 def __next__(self):
2033 if self.i >= len(self.seqn): raise StopIteration
2034 v = self.seqn[self.i]
2035 self.i += 1
2036 return v
2037
2038 class N:
2039 'Iterator missing __next__()'
2040 def __init__(self, seqn):
2041 self.seqn = seqn
2042 self.i = 0
2043 def __iter__(self):
2044 return self
2045
2046 class E:
2047 'Test propagation of exceptions'
2048 def __init__(self, seqn):
2049 self.seqn = seqn
2050 self.i = 0
2051 def __iter__(self):
2052 return self
2053 def __next__(self):
2054 3 // 0
2055
2056 class S:
2057 'Test immediate stop'
2058 def __init__(self, seqn):
2059 pass
2060 def __iter__(self):
2061 return self
2062 def __next__(self):
2063 raise StopIteration
2064
2065 def L(seqn):
2066 'Test multiple tiers of iterators'
2067 return chain(map(lambda x:x, R(Ig(G(seqn)))))
2068
2069
2070 class TestVariousIteratorArgs(unittest.TestCase):
2071
2072 def test_accumulate(self):
2073 s = [1,2,3,4,5]
2074 r = [1,3,6,10,15]
2075 n = len(s)
2076 for g in (G, I, Ig, L, R):
2077 self.assertEqual(list(accumulate(g(s))), r)
2078 self.assertEqual(list(accumulate(S(s))), [])
2079 self.assertRaises(TypeError, accumulate, X(s))
2080 self.assertRaises(TypeError, accumulate, N(s))
2081 self.assertRaises(ZeroDivisionError, list, accumulate(E(s)))
2082
2083 def test_chain(self):
2084 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
2085 for g in (G, I, Ig, S, L, R):
2086 self.assertEqual(list(chain(g(s))), list(g(s)))
2087 self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
2088 self.assertRaises(TypeError, list, chain(X(s)))
2089 self.assertRaises(TypeError, list, chain(N(s)))
2090 self.assertRaises(ZeroDivisionError, list, chain(E(s)))
2091
2092 def test_compress(self):
2093 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
2094 n = len(s)
2095 for g in (G, I, Ig, S, L, R):
2096 self.assertEqual(list(compress(g(s), repeat(1))), list(g(s)))
2097 self.assertRaises(TypeError, compress, X(s), repeat(1))
2098 self.assertRaises(TypeError, compress, N(s), repeat(1))
2099 self.assertRaises(ZeroDivisionError, list, compress(E(s), repeat(1)))
2100
2101 def test_product(self):
2102 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
2103 self.assertRaises(TypeError, product, X(s))
2104 self.assertRaises(TypeError, product, N(s))
2105 self.assertRaises(ZeroDivisionError, product, E(s))
2106
2107 def test_cycle(self):
2108 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
2109 for g in (G, I, Ig, S, L, R):
2110 tgtlen = len(s) * 3
2111 expected = list(g(s))*3
2112 actual = list(islice(cycle(g(s)), tgtlen))
2113 self.assertEqual(actual, expected)
2114 self.assertRaises(TypeError, cycle, X(s))
2115 self.assertRaises(TypeError, cycle, N(s))
2116 self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
2117
2118 def test_groupby(self):
2119 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
2120 for g in (G, I, Ig, S, L, R):
2121 self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
2122 self.assertRaises(TypeError, groupby, X(s))
2123 self.assertRaises(TypeError, groupby, N(s))
2124 self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
2125
2126 def test_filter(self):
2127 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
2128 for g in (G, I, Ig, S, L, R):
2129 self.assertEqual(list(filter(isEven, g(s))),
2130 [x for x in g(s) if isEven(x)])
2131 self.assertRaises(TypeError, filter, isEven, X(s))
2132 self.assertRaises(TypeError, filter, isEven, N(s))
2133 self.assertRaises(ZeroDivisionError, list, filter(isEven, E(s)))
2134
2135 def test_filterfalse(self):
2136 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
2137 for g in (G, I, Ig, S, L, R):
2138 self.assertEqual(list(filterfalse(isEven, g(s))),
2139 [x for x in g(s) if isOdd(x)])
2140 self.assertRaises(TypeError, filterfalse, isEven, X(s))
2141 self.assertRaises(TypeError, filterfalse, isEven, N(s))
2142 self.assertRaises(ZeroDivisionError, list, filterfalse(isEven, E(s)))
2143
2144 def test_zip(self):
2145 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
2146 for g in (G, I, Ig, S, L, R):
2147 self.assertEqual(list(zip(g(s))), lzip(g(s)))
2148 self.assertEqual(list(zip(g(s), g(s))), lzip(g(s), g(s)))
2149 self.assertRaises(TypeError, zip, X(s))
2150 self.assertRaises(TypeError, zip, N(s))
2151 self.assertRaises(ZeroDivisionError, list, zip(E(s)))
2152
2153 def test_ziplongest(self):
2154 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
2155 for g in (G, I, Ig, S, L, R):
2156 self.assertEqual(list(zip_longest(g(s))), list(zip(g(s))))
2157 self.assertEqual(list(zip_longest(g(s), g(s))), list(zip(g(s), g(s))))
2158 self.assertRaises(TypeError, zip_longest, X(s))
2159 self.assertRaises(TypeError, zip_longest, N(s))
2160 self.assertRaises(ZeroDivisionError, list, zip_longest(E(s)))
2161
2162 def test_map(self):
2163 for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
2164 for g in (G, I, Ig, S, L, R):
2165 self.assertEqual(list(map(onearg, g(s))),
2166 [onearg(x) for x in g(s)])
2167 self.assertEqual(list(map(operator.pow, g(s), g(s))),
2168 [x**x for x in g(s)])
2169 self.assertRaises(TypeError, map, onearg, X(s))
2170 self.assertRaises(TypeError, map, onearg, N(s))
2171 self.assertRaises(ZeroDivisionError, list, map(onearg, E(s)))
2172
2173 def test_islice(self):
2174 for s in ("12345", "", range(1000), ('do', 1.2), range(2000,2200,5)):
2175 for g in (G, I, Ig, S, L, R):
2176 self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
2177 self.assertRaises(TypeError, islice, X(s), 10)
2178 self.assertRaises(TypeError, islice, N(s), 10)
2179 self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
2180
2181 def test_pairwise(self):
2182 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
2183 for g in (G, I, Ig, S, L, R):
2184 seq = list(g(s))
2185 expected = list(zip(seq, seq[1:]))
2186 actual = list(pairwise(g(s)))
2187 self.assertEqual(actual, expected)
2188 self.assertRaises(TypeError, pairwise, X(s))
2189 self.assertRaises(TypeError, pairwise, N(s))
2190 self.assertRaises(ZeroDivisionError, list, pairwise(E(s)))
2191
2192 def test_starmap(self):
2193 for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
2194 for g in (G, I, Ig, S, L, R):
2195 ss = lzip(s, s)
2196 self.assertEqual(list(starmap(operator.pow, g(ss))),
2197 [x**x for x in g(s)])
2198 self.assertRaises(TypeError, starmap, operator.pow, X(ss))
2199 self.assertRaises(TypeError, starmap, operator.pow, N(ss))
2200 self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
2201
2202 def test_takewhile(self):
2203 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
2204 for g in (G, I, Ig, S, L, R):
2205 tgt = []
2206 for elem in g(s):
2207 if not isEven(elem): break
2208 tgt.append(elem)
2209 self.assertEqual(list(takewhile(isEven, g(s))), tgt)
2210 self.assertRaises(TypeError, takewhile, isEven, X(s))
2211 self.assertRaises(TypeError, takewhile, isEven, N(s))
2212 self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
2213
2214 def test_dropwhile(self):
2215 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
2216 for g in (G, I, Ig, S, L, R):
2217 tgt = []
2218 for elem in g(s):
2219 if not tgt and isOdd(elem): continue
2220 tgt.append(elem)
2221 self.assertEqual(list(dropwhile(isOdd, g(s))), tgt)
2222 self.assertRaises(TypeError, dropwhile, isOdd, X(s))
2223 self.assertRaises(TypeError, dropwhile, isOdd, N(s))
2224 self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
2225
2226 def test_tee(self):
2227 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
2228 for g in (G, I, Ig, S, L, R):
2229 it1, it2 = tee(g(s))
2230 self.assertEqual(list(it1), list(g(s)))
2231 self.assertEqual(list(it2), list(g(s)))
2232 self.assertRaises(TypeError, tee, X(s))
2233 self.assertRaises(TypeError, tee, N(s))
2234 self.assertRaises(ZeroDivisionError, list, tee(E(s))[0])
2235
2236 class LengthTransparency(unittest.TestCase):
2237
2238 def test_repeat(self):
2239 self.assertEqual(operator.length_hint(repeat(None, 50)), 50)
2240 self.assertEqual(operator.length_hint(repeat(None, 0)), 0)
2241 self.assertEqual(operator.length_hint(repeat(None), 12), 12)
2242
2243 def test_repeat_with_negative_times(self):
2244 self.assertEqual(operator.length_hint(repeat(None, -1)), 0)
2245 self.assertEqual(operator.length_hint(repeat(None, -2)), 0)
2246 self.assertEqual(operator.length_hint(repeat(None, times=-1)), 0)
2247 self.assertEqual(operator.length_hint(repeat(None, times=-2)), 0)
2248
2249 class RegressionTests(unittest.TestCase):
2250
2251 def test_sf_793826(self):
2252 # Fix Armin Rigo's successful efforts to wreak havoc
2253
2254 def mutatingtuple(tuple1, f, tuple2):
2255 # this builds a tuple t which is a copy of tuple1,
2256 # then calls f(t), then mutates t to be equal to tuple2
2257 # (needs len(tuple1) == len(tuple2)).
2258 def g(value, first=[1]):
2259 if first:
2260 del first[:]
2261 f(next(z))
2262 return value
2263 items = list(tuple2)
2264 items[1:1] = list(tuple1)
2265 gen = map(g, items)
2266 z = zip(*[gen]*len(tuple1))
2267 next(z)
2268
2269 def f(t):
2270 global T
2271 T = t
2272 first[:] = list(T)
2273
2274 first = []
2275 mutatingtuple((1,2,3), f, (4,5,6))
2276 second = list(T)
2277 self.assertEqual(first, second)
2278
2279
2280 def test_sf_950057(self):
2281 # Make sure that chain() and cycle() catch exceptions immediately
2282 # rather than when shifting between input sources
2283
2284 def gen1():
2285 hist.append(0)
2286 yield 1
2287 hist.append(1)
2288 raise AssertionError
2289 hist.append(2)
2290
2291 def gen2(x):
2292 hist.append(3)
2293 yield 2
2294 hist.append(4)
2295
2296 hist = []
2297 self.assertRaises(AssertionError, list, chain(gen1(), gen2(False)))
2298 self.assertEqual(hist, [0,1])
2299
2300 hist = []
2301 self.assertRaises(AssertionError, list, chain(gen1(), gen2(True)))
2302 self.assertEqual(hist, [0,1])
2303
2304 hist = []
2305 self.assertRaises(AssertionError, list, cycle(gen1()))
2306 self.assertEqual(hist, [0,1])
2307
2308 @support.skip_if_pgo_task
2309 @support.requires_resource('cpu')
2310 def test_long_chain_of_empty_iterables(self):
2311 # Make sure itertools.chain doesn't run into recursion limits when
2312 # dealing with long chains of empty iterables. Even with a high
2313 # number this would probably only fail in Py_DEBUG mode.
2314 it = chain.from_iterable(() for unused in range(10000000))
2315 with self.assertRaises(StopIteration):
2316 next(it)
2317
2318 def test_issue30347_1(self):
2319 def f(n):
2320 if n == 5:
2321 list(b)
2322 return n != 6
2323 for (k, b) in groupby(range(10), f):
2324 list(b) # shouldn't crash
2325
2326 def test_issue30347_2(self):
2327 class K:
2328 def __init__(self, v):
2329 pass
2330 def __eq__(self, other):
2331 nonlocal i
2332 i += 1
2333 if i == 1:
2334 next(g, None)
2335 return True
2336 i = 0
2337 g = next(groupby(range(10), K))[1]
2338 for j in range(2):
2339 next(g, None) # shouldn't crash
2340
2341
2342 class SubclassWithKwargsTest(unittest.TestCase):
2343 def test_keywords_in_subclass(self):
2344 # count is not subclassable...
2345 testcases = [
2346 (repeat, (1, 2), [1, 1]),
2347 (zip, ([1, 2], 'ab'), [(1, 'a'), (2, 'b')]),
2348 (filter, (None, [0, 1]), [1]),
2349 (filterfalse, (None, [0, 1]), [0]),
2350 (chain, ([1, 2], [3, 4]), [1, 2, 3]),
2351 (map, (str, [1, 2]), ['1', '2']),
2352 (starmap, (operator.pow, ((2, 3), (3, 2))), [8, 9]),
2353 (islice, ([1, 2, 3, 4], 1, 3), [2, 3]),
2354 (takewhile, (isEven, [2, 3, 4]), [2]),
2355 (dropwhile, (isEven, [2, 3, 4]), [3, 4]),
2356 (cycle, ([1, 2],), [1, 2, 1]),
2357 (compress, ('ABC', [1, 0, 1]), ['A', 'C']),
2358 ]
2359 for cls, args, result in testcases:
2360 with self.subTest(cls):
2361 class subclass(cls):
2362 pass
2363 u = subclass(*args)
2364 self.assertIs(type(u), subclass)
2365 self.assertEqual(list(islice(u, 0, 3)), result)
2366 with self.assertRaises(TypeError):
2367 subclass(*args, newarg=3)
2368
2369 for cls, args, result in testcases:
2370 # Constructors of repeat, zip, compress accept keyword arguments.
2371 # Their subclasses need overriding __new__ to support new
2372 # keyword arguments.
2373 if cls in [repeat, zip, compress]:
2374 continue
2375 with self.subTest(cls):
2376 class subclass_with_init(cls):
2377 def __init__(self, *args, newarg=None):
2378 self.newarg = newarg
2379 u = subclass_with_init(*args, newarg=3)
2380 self.assertIs(type(u), subclass_with_init)
2381 self.assertEqual(list(islice(u, 0, 3)), result)
2382 self.assertEqual(u.newarg, 3)
2383
2384 for cls, args, result in testcases:
2385 with self.subTest(cls):
2386 class subclass_with_new(cls):
2387 def __new__(cls, *args, newarg=None):
2388 self = super().__new__(cls, *args)
2389 self.newarg = newarg
2390 return self
2391 u = subclass_with_new(*args, newarg=3)
2392 self.assertIs(type(u), subclass_with_new)
2393 self.assertEqual(list(islice(u, 0, 3)), result)
2394 self.assertEqual(u.newarg, 3)
2395
2396
2397 @support.cpython_only
2398 class SizeofTest(unittest.TestCase):
2399 def setUp(self):
2400 self.ssize_t = struct.calcsize('n')
2401
2402 check_sizeof = support.check_sizeof
2403
2404 def test_product_sizeof(self):
2405 basesize = support.calcobjsize('3Pi')
2406 check = self.check_sizeof
2407 check(product('ab', '12'), basesize + 2 * self.ssize_t)
2408 check(product(*(('abc',) * 10)), basesize + 10 * self.ssize_t)
2409
2410 def test_combinations_sizeof(self):
2411 basesize = support.calcobjsize('3Pni')
2412 check = self.check_sizeof
2413 check(combinations('abcd', 3), basesize + 3 * self.ssize_t)
2414 check(combinations(range(10), 4), basesize + 4 * self.ssize_t)
2415
2416 def test_combinations_with_replacement_sizeof(self):
2417 cwr = combinations_with_replacement
2418 basesize = support.calcobjsize('3Pni')
2419 check = self.check_sizeof
2420 check(cwr('abcd', 3), basesize + 3 * self.ssize_t)
2421 check(cwr(range(10), 4), basesize + 4 * self.ssize_t)
2422
2423 def test_permutations_sizeof(self):
2424 basesize = support.calcobjsize('4Pni')
2425 check = self.check_sizeof
2426 check(permutations('abcd'),
2427 basesize + 4 * self.ssize_t + 4 * self.ssize_t)
2428 check(permutations('abcd', 3),
2429 basesize + 4 * self.ssize_t + 3 * self.ssize_t)
2430 check(permutations('abcde', 3),
2431 basesize + 5 * self.ssize_t + 3 * self.ssize_t)
2432 check(permutations(range(10), 4),
2433 basesize + 10 * self.ssize_t + 4 * self.ssize_t)
2434
2435
2436 def load_tests(loader, tests, pattern):
2437 tests.addTest(doctest.DocTestSuite())
2438 return tests
2439
2440
2441 if __name__ == "__main__":
2442 unittest.main()