blob: f940852ce1b2b8e839147a234e85b742a4731737 [file] [log] [blame]
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Raymond Hettinger96ef8112003-02-01 00:10:11 +00003from itertools import *
Antoine Pitrou26f82ef2014-04-29 12:13:46 +02004import weakref
Raymond Hettinger8a882a72009-02-12 12:08:18 +00005from decimal import Decimal
Raymond Hettingerde09acf2009-02-12 12:53:53 +00006from fractions import Fraction
Raymond Hettinger2012f172003-02-07 05:32:58 +00007import sys
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00008import operator
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00009import random
Raymond Hettingera3e1ad22009-11-30 22:02:31 +000010import copy
11import pickle
Christian Heimesc3f30c42008-02-22 16:37:40 +000012from functools import reduce
Serhiy Storchaka2dae92a2013-12-09 17:45:57 +020013import sys
14import struct
Benjamin Petersonee8712c2008-05-20 21:35:26 +000015maxsize = support.MAX_Py_ssize_t
Guido van Rossum360e4b82007-05-14 22:51:27 +000016minsize = -maxsize-1
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000017
Guido van Rossum801f0d72006-08-24 19:48:10 +000018def lzip(*args):
19 return list(zip(*args))
20
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000021def onearg(x):
22 'Test function of one argument'
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +000023 return 2*x
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000024
25def errfunc(*args):
26 'Test function that raises an error'
27 raise ValueError
28
29def gen3():
30 'Non-restartable source sequence'
31 for i in (0, 1, 2):
32 yield i
33
34def isEven(x):
35 'Test predicate'
36 return x%2==0
37
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +000038def isOdd(x):
39 'Test predicate'
40 return x%2==1
41
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000042def tupleize(*args):
43 return args
44
45def irange(n):
46 for i in range(n):
47 yield i
48
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000049class StopNow:
50 'Class emulating an empty iterable.'
51 def __iter__(self):
52 return self
Georg Brandla18af4e2007-04-21 15:47:16 +000053 def __next__(self):
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000054 raise StopIteration
Raymond Hettinger96ef8112003-02-01 00:10:11 +000055
Raymond Hettinger02420702003-06-29 20:36:23 +000056def take(n, seq):
57 'Convenience function for partially consuming a long of infinite iterable'
58 return list(islice(seq, n))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +000059
Christian Heimes78644762008-03-04 23:39:23 +000060def prod(iterable):
61 return reduce(operator.mul, iterable, 1)
62
Christian Heimes380f7f22008-02-28 11:19:05 +000063def fact(n):
64 'Factorial'
Christian Heimes78644762008-03-04 23:39:23 +000065 return prod(range(1, n+1))
66
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000067# root level methods for pickling ability
68def testR(r):
69 return r[0]
70
71def testR2(r):
72 return r[2]
73
74def underten(x):
75 return x<10
76
Serhiy Storchakabad12572014-12-15 14:03:42 +020077picklecopiers = [lambda s, proto=proto: pickle.loads(pickle.dumps(s, proto))
78 for proto in range(pickle.HIGHEST_PROTOCOL + 1)]
79
Raymond Hettinger96ef8112003-02-01 00:10:11 +000080class TestBasicOps(unittest.TestCase):
Raymond Hettinger482ba772010-12-01 22:48:00 +000081
Serhiy Storchakabad12572014-12-15 14:03:42 +020082 def pickletest(self, protocol, it, stop=4, take=1, compare=None):
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000083 """Test that an iterator is the same after pickling, also when part-consumed"""
84 def expand(it, i=0):
85 # Recursively expand iterables, within sensible bounds
86 if i > 10:
87 raise RuntimeError("infinite recursion encountered")
88 if isinstance(it, str):
89 return it
90 try:
91 l = list(islice(it, stop))
92 except TypeError:
93 return it # can't expand it
94 return [expand(e, i+1) for e in l]
95
96 # Test the initial copy against the original
Serhiy Storchakabad12572014-12-15 14:03:42 +020097 dump = pickle.dumps(it, protocol)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000098 i2 = pickle.loads(dump)
99 self.assertEqual(type(it), type(i2))
100 a, b = expand(it), expand(i2)
101 self.assertEqual(a, b)
102 if compare:
103 c = expand(compare)
104 self.assertEqual(a, c)
105
106 # Take from the copy, and create another copy and compare them.
107 i3 = pickle.loads(dump)
108 took = 0
109 try:
110 for i in range(take):
111 next(i3)
112 took += 1
113 except StopIteration:
114 pass #in case there is less data than 'take'
Serhiy Storchakabad12572014-12-15 14:03:42 +0200115 dump = pickle.dumps(i3, protocol)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000116 i4 = pickle.loads(dump)
117 a, b = expand(i3), expand(i4)
118 self.assertEqual(a, b)
119 if compare:
120 c = expand(compare[took:])
121 self.assertEqual(a, c);
122
Raymond Hettinger482ba772010-12-01 22:48:00 +0000123 def test_accumulate(self):
124 self.assertEqual(list(accumulate(range(10))), # one positional arg
Raymond Hettingerd8ff4652010-12-03 02:09:34 +0000125 [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
126 self.assertEqual(list(accumulate(iterable=range(10))), # kw arg
127 [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
Raymond Hettinger482ba772010-12-01 22:48:00 +0000128 for typ in int, complex, Decimal, Fraction: # multiple types
Raymond Hettingerd8ff4652010-12-03 02:09:34 +0000129 self.assertEqual(
130 list(accumulate(map(typ, range(10)))),
Raymond Hettinger482ba772010-12-01 22:48:00 +0000131 list(map(typ, [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])))
Raymond Hettinger2d93e6e2010-12-03 02:33:53 +0000132 self.assertEqual(list(accumulate('abc')), ['a', 'ab', 'abc']) # works with non-numeric
Raymond Hettinger482ba772010-12-01 22:48:00 +0000133 self.assertEqual(list(accumulate([])), []) # empty iterable
Raymond Hettingerd8ff4652010-12-03 02:09:34 +0000134 self.assertEqual(list(accumulate([7])), [7]) # iterable of length one
Raymond Hettinger5d446132011-03-27 18:52:10 -0700135 self.assertRaises(TypeError, accumulate, range(10), 5, 6) # too many args
Raymond Hettinger482ba772010-12-01 22:48:00 +0000136 self.assertRaises(TypeError, accumulate) # too few args
Raymond Hettingerd8ff4652010-12-03 02:09:34 +0000137 self.assertRaises(TypeError, accumulate, x=range(10)) # unexpected kwd arg
Raymond Hettinger482ba772010-12-01 22:48:00 +0000138 self.assertRaises(TypeError, list, accumulate([1, []])) # args that don't add
139
Raymond Hettinger5d446132011-03-27 18:52:10 -0700140 s = [2, 8, 9, 5, 7, 0, 3, 4, 1, 6]
141 self.assertEqual(list(accumulate(s, min)),
142 [2, 2, 2, 2, 2, 0, 0, 0, 0, 0])
143 self.assertEqual(list(accumulate(s, max)),
144 [2, 8, 9, 9, 9, 9, 9, 9, 9, 9])
145 self.assertEqual(list(accumulate(s, operator.mul)),
146 [2, 16, 144, 720, 5040, 0, 0, 0, 0, 0])
147 with self.assertRaises(TypeError):
148 list(accumulate(s, chr)) # unary-operation
Serhiy Storchakabad12572014-12-15 14:03:42 +0200149 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
150 self.pickletest(proto, accumulate(range(10))) # test pickling
Raymond Hettinger5d446132011-03-27 18:52:10 -0700151
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000152 def test_chain(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000153
154 def chain2(*iterables):
155 'Pure python version in the docs'
156 for it in iterables:
157 for element in it:
158 yield element
159
160 for c in (chain, chain2):
161 self.assertEqual(list(c('abc', 'def')), list('abcdef'))
162 self.assertEqual(list(c('abc')), list('abc'))
163 self.assertEqual(list(c('')), [])
164 self.assertEqual(take(4, c('abc', 'def')), list('abcd'))
165 self.assertRaises(TypeError, list,c(2, 3))
Christian Heimesf16baeb2008-02-29 14:57:44 +0000166
167 def test_chain_from_iterable(self):
168 self.assertEqual(list(chain.from_iterable(['abc', 'def'])), list('abcdef'))
169 self.assertEqual(list(chain.from_iterable(['abc'])), list('abc'))
170 self.assertEqual(list(chain.from_iterable([''])), [])
171 self.assertEqual(take(4, chain.from_iterable(['abc', 'def'])), list('abcd'))
172 self.assertRaises(TypeError, list, chain.from_iterable([2, 3]))
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000173
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000174 def test_chain_reducible(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200175 for oper in [copy.deepcopy] + picklecopiers:
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000176 it = chain('abc', 'def')
177 self.assertEqual(list(oper(it)), list('abcdef'))
178 self.assertEqual(next(it), 'a')
179 self.assertEqual(list(oper(it)), list('bcdef'))
180
181 self.assertEqual(list(oper(chain(''))), [])
182 self.assertEqual(take(4, oper(chain('abc', 'def'))), list('abcd'))
183 self.assertRaises(TypeError, list, oper(chain(2, 3)))
Serhiy Storchakabad12572014-12-15 14:03:42 +0200184 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
185 self.pickletest(proto, chain('abc', 'def'), compare=list('abcdef'))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000186
Christian Heimes380f7f22008-02-28 11:19:05 +0000187 def test_combinations(self):
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000188 self.assertRaises(TypeError, combinations, 'abc') # missing r argument
Christian Heimes380f7f22008-02-28 11:19:05 +0000189 self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments
Christian Heimes78644762008-03-04 23:39:23 +0000190 self.assertRaises(TypeError, combinations, None) # pool is not iterable
Christian Heimes380f7f22008-02-28 11:19:05 +0000191 self.assertRaises(ValueError, combinations, 'abc', -2) # r is negative
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000192
Serhiy Storchakabad12572014-12-15 14:03:42 +0200193 for op in [lambda a:a] + picklecopiers:
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000194 self.assertEqual(list(op(combinations('abc', 32))), []) # r > n
195
196 self.assertEqual(list(op(combinations('ABCD', 2))),
197 [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
198 testIntermediate = combinations('ABCD', 2)
199 next(testIntermediate)
200 self.assertEqual(list(op(testIntermediate)),
201 [('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
202
203 self.assertEqual(list(op(combinations(range(4), 3))),
204 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
205 testIntermediate = combinations(range(4), 3)
206 next(testIntermediate)
207 self.assertEqual(list(op(testIntermediate)),
208 [(0,1,3), (0,2,3), (1,2,3)])
209
Christian Heimes78644762008-03-04 23:39:23 +0000210
211 def combinations1(iterable, r):
212 'Pure python version shown in the docs'
213 pool = tuple(iterable)
214 n = len(pool)
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000215 if r > n:
216 return
Christian Heimes78644762008-03-04 23:39:23 +0000217 indices = list(range(r))
218 yield tuple(pool[i] for i in indices)
219 while 1:
220 for i in reversed(range(r)):
221 if indices[i] != i + n - r:
222 break
223 else:
224 return
225 indices[i] += 1
226 for j in range(i+1, r):
227 indices[j] = indices[j-1] + 1
228 yield tuple(pool[i] for i in indices)
229
230 def combinations2(iterable, r):
231 'Pure python version shown in the docs'
232 pool = tuple(iterable)
233 n = len(pool)
234 for indices in permutations(range(n), r):
235 if sorted(indices) == list(indices):
236 yield tuple(pool[i] for i in indices)
237
Raymond Hettingereb508ad2009-01-27 09:35:21 +0000238 def combinations3(iterable, r):
239 'Pure python version from cwr()'
240 pool = tuple(iterable)
241 n = len(pool)
242 for indices in combinations_with_replacement(range(n), r):
243 if len(set(indices)) == r:
244 yield tuple(pool[i] for i in indices)
245
Christian Heimes78644762008-03-04 23:39:23 +0000246 for n in range(7):
Christian Heimes380f7f22008-02-28 11:19:05 +0000247 values = [5*x-12 for x in range(n)]
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000248 for r in range(n+2):
Christian Heimes380f7f22008-02-28 11:19:05 +0000249 result = list(combinations(values, r))
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000250 self.assertEqual(len(result), 0 if r>n else fact(n) / fact(r) / fact(n-r)) # right number of combs
Christian Heimes380f7f22008-02-28 11:19:05 +0000251 self.assertEqual(len(result), len(set(result))) # no repeats
252 self.assertEqual(result, sorted(result)) # lexicographic order
253 for c in result:
254 self.assertEqual(len(c), r) # r-length combinations
255 self.assertEqual(len(set(c)), r) # no duplicate elements
256 self.assertEqual(list(c), sorted(c)) # keep original ordering
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000257 self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000258 self.assertEqual(list(c),
259 [e for e in values if e in c]) # comb is a subsequence of the input iterable
Christian Heimes78644762008-03-04 23:39:23 +0000260 self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000261 self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version
Raymond Hettingereb508ad2009-01-27 09:35:21 +0000262 self.assertEqual(result, list(combinations3(values, r))) # matches second pure python version
Christian Heimes78644762008-03-04 23:39:23 +0000263
Serhiy Storchakabad12572014-12-15 14:03:42 +0200264 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
265 self.pickletest(proto, combinations(values, r)) # test pickling
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000266
Benjamin Peterson4b40eeb2015-02-01 20:59:00 -0500267 @support.bigaddrspacetest
268 def test_combinations_overflow(self):
Serhiy Storchakadee948b2015-02-03 01:34:09 +0200269 with self.assertRaises((OverflowError, MemoryError)):
Benjamin Peterson4b40eeb2015-02-01 20:59:00 -0500270 combinations("AA", 2**29)
271
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000272 # Test implementation detail: tuple re-use
Alex Gaynore151d212011-07-17 16:21:30 -0700273 @support.impl_detail("tuple reuse is specific to CPython")
274 def test_combinations_tuple_reuse(self):
Christian Heimes78644762008-03-04 23:39:23 +0000275 self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1)
276 self.assertNotEqual(len(set(map(id, list(combinations('abcde', 3))))), 1)
277
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000278 def test_combinations_with_replacement(self):
279 cwr = combinations_with_replacement
280 self.assertRaises(TypeError, cwr, 'abc') # missing r argument
281 self.assertRaises(TypeError, cwr, 'abc', 2, 1) # too many arguments
282 self.assertRaises(TypeError, cwr, None) # pool is not iterable
283 self.assertRaises(ValueError, cwr, 'abc', -2) # r is negative
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000284
Serhiy Storchakabad12572014-12-15 14:03:42 +0200285 for op in [lambda a:a] + picklecopiers:
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000286 self.assertEqual(list(op(cwr('ABC', 2))),
287 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
288 testIntermediate = cwr('ABC', 2)
289 next(testIntermediate)
290 self.assertEqual(list(op(testIntermediate)),
291 [('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
292
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000293
294 def cwr1(iterable, r):
295 'Pure python version shown in the docs'
296 # number items returned: (n+r-1)! / r! / (n-1)! when n>0
297 pool = tuple(iterable)
298 n = len(pool)
299 if not n and r:
300 return
301 indices = [0] * r
302 yield tuple(pool[i] for i in indices)
303 while 1:
304 for i in reversed(range(r)):
305 if indices[i] != n - 1:
306 break
307 else:
308 return
309 indices[i:] = [indices[i] + 1] * (r - i)
310 yield tuple(pool[i] for i in indices)
311
312 def cwr2(iterable, r):
313 'Pure python version shown in the docs'
314 pool = tuple(iterable)
315 n = len(pool)
316 for indices in product(range(n), repeat=r):
317 if sorted(indices) == list(indices):
318 yield tuple(pool[i] for i in indices)
319
320 def numcombs(n, r):
321 if not n:
322 return 0 if r else 1
323 return fact(n+r-1) / fact(r)/ fact(n-1)
324
325 for n in range(7):
326 values = [5*x-12 for x in range(n)]
327 for r in range(n+2):
328 result = list(cwr(values, r))
329
330 self.assertEqual(len(result), numcombs(n, r)) # right number of combs
331 self.assertEqual(len(result), len(set(result))) # no repeats
332 self.assertEqual(result, sorted(result)) # lexicographic order
333
334 regular_combs = list(combinations(values, r)) # compare to combs without replacement
335 if n == 0 or r <= 1:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000336 self.assertEqual(result, regular_combs) # cases that should be identical
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000337 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000338 self.assertTrue(set(result) >= set(regular_combs)) # rest should be supersets of regular combs
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000339
340 for c in result:
341 self.assertEqual(len(c), r) # r-length combinations
342 noruns = [k for k,v in groupby(c)] # combo without consecutive repeats
343 self.assertEqual(len(noruns), len(set(noruns))) # no repeats other than consecutive
344 self.assertEqual(list(c), sorted(c)) # keep original ordering
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000345 self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000346 self.assertEqual(noruns,
347 [e for e in values if e in c]) # comb is a subsequence of the input iterable
348 self.assertEqual(result, list(cwr1(values, r))) # matches first pure python version
349 self.assertEqual(result, list(cwr2(values, r))) # matches second pure python version
350
Serhiy Storchakabad12572014-12-15 14:03:42 +0200351 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
352 self.pickletest(proto, cwr(values,r)) # test pickling
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000353
Benjamin Peterson6f082292015-02-01 21:10:47 -0500354 @support.bigaddrspacetest
355 def test_combinations_with_replacement_overflow(self):
Serhiy Storchakadee948b2015-02-03 01:34:09 +0200356 with self.assertRaises((OverflowError, MemoryError)):
Benjamin Peterson6f082292015-02-01 21:10:47 -0500357 combinations_with_replacement("AA", 2**30)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000358
Benjamin Peterson6f082292015-02-01 21:10:47 -0500359 # Test implementation detail: tuple re-use
Alex Gaynore151d212011-07-17 16:21:30 -0700360 @support.impl_detail("tuple reuse is specific to CPython")
361 def test_combinations_with_replacement_tuple_reuse(self):
362 cwr = combinations_with_replacement
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000363 self.assertEqual(len(set(map(id, cwr('abcde', 3)))), 1)
364 self.assertNotEqual(len(set(map(id, list(cwr('abcde', 3))))), 1)
365
Christian Heimes78644762008-03-04 23:39:23 +0000366 def test_permutations(self):
367 self.assertRaises(TypeError, permutations) # too few arguments
368 self.assertRaises(TypeError, permutations, 'abc', 2, 1) # too many arguments
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000369 self.assertRaises(TypeError, permutations, None) # pool is not iterable
370 self.assertRaises(ValueError, permutations, 'abc', -2) # r is negative
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000371 self.assertEqual(list(permutations('abc', 32)), []) # r > n
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000372 self.assertRaises(TypeError, permutations, 'abc', 's') # r is not an int or None
Christian Heimes78644762008-03-04 23:39:23 +0000373 self.assertEqual(list(permutations(range(3), 2)),
374 [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)])
375
376 def permutations1(iterable, r=None):
377 'Pure python version shown in the docs'
378 pool = tuple(iterable)
379 n = len(pool)
380 r = n if r is None else r
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000381 if r > n:
382 return
Christian Heimes78644762008-03-04 23:39:23 +0000383 indices = list(range(n))
384 cycles = list(range(n-r+1, n+1))[::-1]
385 yield tuple(pool[i] for i in indices[:r])
386 while n:
387 for i in reversed(range(r)):
388 cycles[i] -= 1
389 if cycles[i] == 0:
390 indices[i:] = indices[i+1:] + indices[i:i+1]
391 cycles[i] = n - i
392 else:
393 j = cycles[i]
394 indices[i], indices[-j] = indices[-j], indices[i]
395 yield tuple(pool[i] for i in indices[:r])
396 break
397 else:
398 return
399
400 def permutations2(iterable, r=None):
401 'Pure python version shown in the docs'
402 pool = tuple(iterable)
403 n = len(pool)
404 r = n if r is None else r
405 for indices in product(range(n), repeat=r):
406 if len(set(indices)) == r:
407 yield tuple(pool[i] for i in indices)
408
409 for n in range(7):
410 values = [5*x-12 for x in range(n)]
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000411 for r in range(n+2):
Christian Heimes78644762008-03-04 23:39:23 +0000412 result = list(permutations(values, r))
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000413 self.assertEqual(len(result), 0 if r>n else fact(n) / fact(n-r)) # right number of perms
Christian Heimes78644762008-03-04 23:39:23 +0000414 self.assertEqual(len(result), len(set(result))) # no repeats
415 self.assertEqual(result, sorted(result)) # lexicographic order
416 for p in result:
417 self.assertEqual(len(p), r) # r-length permutations
418 self.assertEqual(len(set(p)), r) # no duplicate elements
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000419 self.assertTrue(all(e in values for e in p)) # elements taken from input iterable
Christian Heimes78644762008-03-04 23:39:23 +0000420 self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000421 self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version
Christian Heimes78644762008-03-04 23:39:23 +0000422 if r == n:
423 self.assertEqual(result, list(permutations(values, None))) # test r as None
424 self.assertEqual(result, list(permutations(values))) # test default r
425
Serhiy Storchakabad12572014-12-15 14:03:42 +0200426 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
427 self.pickletest(proto, permutations(values, r)) # test pickling
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000428
Benjamin Peterson0eaabf12015-02-01 21:34:07 -0500429 @support.bigaddrspacetest
430 def test_permutations_overflow(self):
Serhiy Storchakadee948b2015-02-03 01:34:09 +0200431 with self.assertRaises((OverflowError, MemoryError)):
Benjamin Peterson0eaabf12015-02-01 21:34:07 -0500432 permutations("A", 2**30)
Benjamin Peterson0eaabf12015-02-01 21:34:07 -0500433
Zachary Waredca807b2014-04-24 13:22:05 -0500434 @support.impl_detail("tuple reuse is specific to CPython")
Alex Gaynore151d212011-07-17 16:21:30 -0700435 def test_permutations_tuple_reuse(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000436 self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1)
Christian Heimes78644762008-03-04 23:39:23 +0000437 self.assertNotEqual(len(set(map(id, list(permutations('abcde', 3))))), 1)
Christian Heimes380f7f22008-02-28 11:19:05 +0000438
Raymond Hettingereb508ad2009-01-27 09:35:21 +0000439 def test_combinatorics(self):
440 # Test relationships between product(), permutations(),
441 # combinations() and combinations_with_replacement().
442
Raymond Hettingerda6bc522009-01-27 10:39:42 +0000443 for n in range(6):
444 s = 'ABCDEFG'[:n]
445 for r in range(8):
446 prod = list(product(s, repeat=r))
447 cwr = list(combinations_with_replacement(s, r))
448 perm = list(permutations(s, r))
449 comb = list(combinations(s, r))
Raymond Hettingereb508ad2009-01-27 09:35:21 +0000450
Raymond Hettingerda6bc522009-01-27 10:39:42 +0000451 # Check size
Ezio Melottib3aedd42010-11-20 19:04:17 +0000452 self.assertEqual(len(prod), n**r)
453 self.assertEqual(len(cwr), (fact(n+r-1) / fact(r)/ fact(n-1)) if n else (not r))
454 self.assertEqual(len(perm), 0 if r>n else fact(n) / fact(n-r))
455 self.assertEqual(len(comb), 0 if r>n else fact(n) / fact(r) / fact(n-r))
Raymond Hettingerda6bc522009-01-27 10:39:42 +0000456
457 # Check lexicographic order without repeated tuples
Ezio Melottib3aedd42010-11-20 19:04:17 +0000458 self.assertEqual(prod, sorted(set(prod)))
459 self.assertEqual(cwr, sorted(set(cwr)))
460 self.assertEqual(perm, sorted(set(perm)))
461 self.assertEqual(comb, sorted(set(comb)))
Raymond Hettingerda6bc522009-01-27 10:39:42 +0000462
463 # Check interrelationships
Ezio Melottib3aedd42010-11-20 19:04:17 +0000464 self.assertEqual(cwr, [t for t in prod if sorted(t)==list(t)]) # cwr: prods which are sorted
465 self.assertEqual(perm, [t for t in prod if len(set(t))==r]) # perm: prods with no dups
Raymond Hettingerda6bc522009-01-27 10:39:42 +0000466 self.assertEqual(comb, [t for t in perm if sorted(t)==list(t)]) # comb: perms that are sorted
467 self.assertEqual(comb, [t for t in cwr if len(set(t))==r]) # comb: cwrs without dups
468 self.assertEqual(comb, list(filter(set(cwr).__contains__, perm))) # comb: perm that is a cwr
469 self.assertEqual(comb, list(filter(set(perm).__contains__, cwr))) # comb: cwr that is a perm
470 self.assertEqual(comb, sorted(set(cwr) & set(perm))) # comb: both a cwr and a perm
Raymond Hettingereb508ad2009-01-27 09:35:21 +0000471
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +0000472 def test_compress(self):
Raymond Hettinger15a49502009-02-19 02:17:09 +0000473 self.assertEqual(list(compress(data='ABCDEF', selectors=[1,0,1,0,1,1])), list('ACEF'))
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +0000474 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
475 self.assertEqual(list(compress('ABCDEF', [0,0,0,0,0,0])), list(''))
476 self.assertEqual(list(compress('ABCDEF', [1,1,1,1,1,1])), list('ABCDEF'))
477 self.assertEqual(list(compress('ABCDEF', [1,0,1])), list('AC'))
478 self.assertEqual(list(compress('ABC', [0,1,1,1,1,1])), list('BC'))
479 n = 10000
480 data = chain.from_iterable(repeat(range(6), n))
481 selectors = chain.from_iterable(repeat((0, 1)))
482 self.assertEqual(list(compress(data, selectors)), [1,3,5] * n)
483 self.assertRaises(TypeError, compress, None, range(6)) # 1st arg not iterable
484 self.assertRaises(TypeError, compress, range(6), None) # 2nd arg not iterable
485 self.assertRaises(TypeError, compress, range(6)) # too few args
486 self.assertRaises(TypeError, compress, range(6), None) # too many args
487
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000488 # check copy, deepcopy, pickle
Serhiy Storchakabad12572014-12-15 14:03:42 +0200489 for op in [lambda a:copy.copy(a), lambda a:copy.deepcopy(a)] + picklecopiers:
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000490 for data, selectors, result1, result2 in [
491 ('ABCDEF', [1,0,1,0,1,1], 'ACEF', 'CEF'),
492 ('ABCDEF', [0,0,0,0,0,0], '', ''),
493 ('ABCDEF', [1,1,1,1,1,1], 'ABCDEF', 'BCDEF'),
494 ('ABCDEF', [1,0,1], 'AC', 'C'),
495 ('ABC', [0,1,1,1,1,1], 'BC', 'C'),
496 ]:
497
498 self.assertEqual(list(op(compress(data=data, selectors=selectors))), list(result1))
499 self.assertEqual(list(op(compress(data, selectors))), list(result1))
500 testIntermediate = compress(data, selectors)
501 if result1:
502 next(testIntermediate)
503 self.assertEqual(list(op(testIntermediate)), list(result2))
504
505
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000506 def test_count(self):
Guido van Rossum801f0d72006-08-24 19:48:10 +0000507 self.assertEqual(lzip('abc',count()), [('a', 0), ('b', 1), ('c', 2)])
508 self.assertEqual(lzip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)])
509 self.assertEqual(take(2, lzip('abc',count(3))), [('a', 3), ('b', 4)])
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000510 self.assertEqual(take(2, zip('abc',count(-1))), [('a', -1), ('b', 0)])
511 self.assertEqual(take(2, zip('abc',count(-3))), [('a', -3), ('b', -2)])
Raymond Hettinger30729212009-02-12 06:28:27 +0000512 self.assertRaises(TypeError, count, 2, 3, 4)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000513 self.assertRaises(TypeError, count, 'a')
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000514 self.assertEqual(list(islice(count(maxsize-5), 10)),
515 list(range(maxsize-5, maxsize+5)))
516 self.assertEqual(list(islice(count(-maxsize-5), 10)),
517 list(range(-maxsize-5, -maxsize+5)))
Kristjan Valur Jonsson35722a92011-03-30 11:04:28 +0000518 self.assertEqual(list(islice(count(10, maxsize+5), 3)),
519 list(range(10, 10+3*(maxsize+5), maxsize+5)))
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000520 c = count(3)
521 self.assertEqual(repr(c), 'count(3)')
Georg Brandla18af4e2007-04-21 15:47:16 +0000522 next(c)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000523 self.assertEqual(repr(c), 'count(4)')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000524 c = count(-9)
525 self.assertEqual(repr(c), 'count(-9)')
Georg Brandla18af4e2007-04-21 15:47:16 +0000526 next(c)
Raymond Hettinger30729212009-02-12 06:28:27 +0000527 self.assertEqual(repr(count(10.25)), 'count(10.25)')
Georg Brandla18af4e2007-04-21 15:47:16 +0000528 self.assertEqual(next(c), -8)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000529 for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300530 # Test repr
531 r1 = repr(count(i))
532 r2 = 'count(%r)'.__mod__(i)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000533 self.assertEqual(r1, r2)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000534
Raymond Hettingera3e1ad22009-11-30 22:02:31 +0000535 # check copy, deepcopy, pickle
536 for value in -3, 3, maxsize-5, maxsize+5:
537 c = count(value)
538 self.assertEqual(next(copy.copy(c)), value)
539 self.assertEqual(next(copy.deepcopy(c)), value)
Serhiy Storchakabad12572014-12-15 14:03:42 +0200540 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
541 self.pickletest(proto, count(value))
Raymond Hettingera3e1ad22009-11-30 22:02:31 +0000542
Kristjan Valur Jonsson35722a92011-03-30 11:04:28 +0000543 #check proper internal error handling for large "step' sizes
544 count(1, maxsize+5); sys.exc_info()
545
Raymond Hettinger30729212009-02-12 06:28:27 +0000546 def test_count_with_stride(self):
547 self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
Raymond Hettingereb13fdd2009-02-21 22:30:12 +0000548 self.assertEqual(lzip('abc',count(start=2,step=3)),
549 [('a', 2), ('b', 5), ('c', 8)])
550 self.assertEqual(lzip('abc',count(step=-1)),
551 [('a', 0), ('b', -1), ('c', -2)])
Raymond Hettinger30729212009-02-12 06:28:27 +0000552 self.assertEqual(lzip('abc',count(2,0)), [('a', 2), ('b', 2), ('c', 2)])
553 self.assertEqual(lzip('abc',count(2,1)), [('a', 2), ('b', 3), ('c', 4)])
Raymond Hettinger9e8dbbc2009-02-14 04:21:49 +0000554 self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
Raymond Hettinger30729212009-02-12 06:28:27 +0000555 self.assertEqual(take(20, count(maxsize-15, 3)), take(20, range(maxsize-15, maxsize+100, 3)))
556 self.assertEqual(take(20, count(-maxsize-15, 3)), take(20, range(-maxsize-15,-maxsize+100, 3)))
557 self.assertEqual(take(3, count(2, 3.25-4j)), [2, 5.25-4j, 8.5-8j])
Raymond Hettinger8a882a72009-02-12 12:08:18 +0000558 self.assertEqual(take(3, count(Decimal('1.1'), Decimal('.1'))),
559 [Decimal('1.1'), Decimal('1.2'), Decimal('1.3')])
Raymond Hettingerde09acf2009-02-12 12:53:53 +0000560 self.assertEqual(take(3, count(Fraction(2,3), Fraction(1,7))),
561 [Fraction(2,3), Fraction(17,21), Fraction(20,21)])
Raymond Hettinger30729212009-02-12 06:28:27 +0000562 self.assertEqual(repr(take(3, count(10, 2.5))), repr([10, 12.5, 15.0]))
563 c = count(3, 5)
564 self.assertEqual(repr(c), 'count(3, 5)')
565 next(c)
566 self.assertEqual(repr(c), 'count(8, 5)')
567 c = count(-9, 0)
568 self.assertEqual(repr(c), 'count(-9, 0)')
569 next(c)
570 self.assertEqual(repr(c), 'count(-9, 0)')
571 c = count(-9, -3)
572 self.assertEqual(repr(c), 'count(-9, -3)')
573 next(c)
574 self.assertEqual(repr(c), 'count(-12, -3)')
575 self.assertEqual(repr(c), 'count(-12, -3)')
576 self.assertEqual(repr(count(10.5, 1.25)), 'count(10.5, 1.25)')
577 self.assertEqual(repr(count(10.5, 1)), 'count(10.5)') # suppress step=1 when it's an int
578 self.assertEqual(repr(count(10.5, 1.00)), 'count(10.5, 1.0)') # do show float values lilke 1.0
579 for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5):
580 for j in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 1, 10, sys.maxsize-5, sys.maxsize+5):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300581 # Test repr
582 r1 = repr(count(i, j))
Raymond Hettinger30729212009-02-12 06:28:27 +0000583 if j == 1:
Serhiy Storchaka95949422013-08-27 19:40:23 +0300584 r2 = ('count(%r)' % i)
Raymond Hettinger30729212009-02-12 06:28:27 +0000585 else:
Serhiy Storchaka95949422013-08-27 19:40:23 +0300586 r2 = ('count(%r, %r)' % (i, j))
Raymond Hettinger30729212009-02-12 06:28:27 +0000587 self.assertEqual(r1, r2)
Serhiy Storchakabad12572014-12-15 14:03:42 +0200588 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
589 self.pickletest(proto, count(i, j))
Raymond Hettinger30729212009-02-12 06:28:27 +0000590
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000591 def test_cycle(self):
Raymond Hettinger02420702003-06-29 20:36:23 +0000592 self.assertEqual(take(10, cycle('abc')), list('abcabcabca'))
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000593 self.assertEqual(list(cycle('')), [])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000594 self.assertRaises(TypeError, cycle)
595 self.assertRaises(TypeError, cycle, 5)
596 self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000597
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000598 # check copy, deepcopy, pickle
599 c = cycle('abc')
600 self.assertEqual(next(c), 'a')
601 #simple copy currently not supported, because __reduce__ returns
602 #an internal iterator
603 #self.assertEqual(take(10, copy.copy(c)), list('bcabcabcab'))
604 self.assertEqual(take(10, copy.deepcopy(c)), list('bcabcabcab'))
Serhiy Storchakabad12572014-12-15 14:03:42 +0200605 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
606 self.assertEqual(take(10, pickle.loads(pickle.dumps(c, proto))),
607 list('bcabcabcab'))
608 next(c)
609 self.assertEqual(take(10, pickle.loads(pickle.dumps(c, proto))),
610 list('cabcabcabc'))
611 next(c)
612 next(c)
613 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
614 self.pickletest(proto, cycle('abc'))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000615
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000616 def test_groupby(self):
617 # Check whether it accepts arguments correctly
618 self.assertEqual([], list(groupby([])))
619 self.assertEqual([], list(groupby([], key=id)))
620 self.assertRaises(TypeError, list, groupby('abc', []))
621 self.assertRaises(TypeError, groupby, None)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000622 self.assertRaises(TypeError, groupby, 'abc', lambda x:x, 10)
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000623
624 # Check normal input
625 s = [(0, 10, 20), (0, 11,21), (0,12,21), (1,13,21), (1,14,22),
626 (2,15,22), (3,16,23), (3,17,23)]
627 dup = []
628 for k, g in groupby(s, lambda r:r[0]):
629 for elem in g:
630 self.assertEqual(k, elem[0])
631 dup.append(elem)
632 self.assertEqual(s, dup)
633
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000634 # Check normal pickled
Serhiy Storchakabad12572014-12-15 14:03:42 +0200635 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
636 dup = []
637 for k, g in pickle.loads(pickle.dumps(groupby(s, testR), proto)):
638 for elem in g:
639 self.assertEqual(k, elem[0])
640 dup.append(elem)
641 self.assertEqual(s, dup)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000642
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000643 # Check nested case
644 dup = []
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000645 for k, g in groupby(s, testR):
646 for ik, ig in groupby(g, testR2):
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000647 for elem in ig:
648 self.assertEqual(k, elem[0])
649 self.assertEqual(ik, elem[2])
650 dup.append(elem)
651 self.assertEqual(s, dup)
652
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000653 # Check nested and pickled
Serhiy Storchakabad12572014-12-15 14:03:42 +0200654 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
655 dup = []
656 for k, g in pickle.loads(pickle.dumps(groupby(s, testR), proto)):
657 for ik, ig in pickle.loads(pickle.dumps(groupby(g, testR2), proto)):
658 for elem in ig:
659 self.assertEqual(k, elem[0])
660 self.assertEqual(ik, elem[2])
661 dup.append(elem)
662 self.assertEqual(s, dup)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000663
664
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000665 # Check case where inner iterator is not used
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000666 keys = [k for k, g in groupby(s, testR)]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000667 expectedkeys = set([r[0] for r in s])
668 self.assertEqual(set(keys), expectedkeys)
669 self.assertEqual(len(keys), len(expectedkeys))
670
671 # Exercise pipes and filters style
672 s = 'abracadabra'
673 # sort s | uniq
Raymond Hettinger64958a12003-12-17 20:43:33 +0000674 r = [k for k, g in groupby(sorted(s))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000675 self.assertEqual(r, ['a', 'b', 'c', 'd', 'r'])
676 # sort s | uniq -d
Raymond Hettinger64958a12003-12-17 20:43:33 +0000677 r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000678 self.assertEqual(r, ['a', 'b', 'r'])
679 # sort s | uniq -c
Raymond Hettinger64958a12003-12-17 20:43:33 +0000680 r = [(len(list(g)), k) for k, g in groupby(sorted(s))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000681 self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')])
682 # sort s | uniq -c | sort -rn | head -3
Raymond Hettinger64958a12003-12-17 20:43:33 +0000683 r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000684 self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')])
685
Georg Brandla18af4e2007-04-21 15:47:16 +0000686 # iter.__next__ failure
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000687 class ExpectedError(Exception):
688 pass
689 def delayed_raise(n=0):
690 for i in range(n):
691 yield 'yo'
692 raise ExpectedError
693 def gulp(iterable, keyp=None, func=list):
694 return [func(g) for k, g in groupby(iterable, keyp)]
695
Georg Brandla18af4e2007-04-21 15:47:16 +0000696 # iter.__next__ failure on outer object
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000697 self.assertRaises(ExpectedError, gulp, delayed_raise(0))
Georg Brandla18af4e2007-04-21 15:47:16 +0000698 # iter.__next__ failure on inner object
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000699 self.assertRaises(ExpectedError, gulp, delayed_raise(1))
700
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +0200701 # __eq__ failure
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000702 class DummyCmp:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000703 def __eq__(self, dst):
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000704 raise ExpectedError
705 s = [DummyCmp(), DummyCmp(), None]
706
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000707 # __eq__ failure on outer object
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000708 self.assertRaises(ExpectedError, gulp, s, func=id)
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000709 # __eq__ failure on inner object
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000710 self.assertRaises(ExpectedError, gulp, s)
711
712 # keyfunc failure
713 def keyfunc(obj):
714 if keyfunc.skip > 0:
715 keyfunc.skip -= 1
716 return obj
717 else:
718 raise ExpectedError
719
720 # keyfunc failure on outer object
721 keyfunc.skip = 0
722 self.assertRaises(ExpectedError, gulp, [None], keyfunc)
723 keyfunc.skip = 1
724 self.assertRaises(ExpectedError, gulp, [None, None], keyfunc)
725
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000726 def test_filter(self):
727 self.assertEqual(list(filter(isEven, range(6))), [0,2,4])
728 self.assertEqual(list(filter(None, [0,1,0,2,0])), [1,2])
729 self.assertEqual(list(filter(bool, [0,1,0,2,0])), [1,2])
730 self.assertEqual(take(4, filter(isEven, count())), [0,2,4,6])
731 self.assertRaises(TypeError, filter)
732 self.assertRaises(TypeError, filter, lambda x:x)
733 self.assertRaises(TypeError, filter, lambda x:x, range(6), 7)
734 self.assertRaises(TypeError, filter, isEven, 3)
735 self.assertRaises(TypeError, next, filter(range(6), range(6)))
Raymond Hettinger60eca932003-02-09 06:40:58 +0000736
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000737 # check copy, deepcopy, pickle
738 ans = [0,2,4]
739
740 c = filter(isEven, range(6))
741 self.assertEqual(list(copy.copy(c)), ans)
742 c = filter(isEven, range(6))
743 self.assertEqual(list(copy.deepcopy(c)), ans)
Serhiy Storchakabad12572014-12-15 14:03:42 +0200744 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
745 c = filter(isEven, range(6))
746 self.assertEqual(list(pickle.loads(pickle.dumps(c, proto))), ans)
747 next(c)
748 self.assertEqual(list(pickle.loads(pickle.dumps(c, proto))), ans[1:])
749 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
750 c = filter(isEven, range(6))
751 self.pickletest(proto, c)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000752
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000753 def test_filterfalse(self):
754 self.assertEqual(list(filterfalse(isEven, range(6))), [1,3,5])
755 self.assertEqual(list(filterfalse(None, [0,1,0,2,0])), [0,0,0])
756 self.assertEqual(list(filterfalse(bool, [0,1,0,2,0])), [0,0,0])
757 self.assertEqual(take(4, filterfalse(isEven, count())), [1,3,5,7])
758 self.assertRaises(TypeError, filterfalse)
759 self.assertRaises(TypeError, filterfalse, lambda x:x)
760 self.assertRaises(TypeError, filterfalse, lambda x:x, range(6), 7)
761 self.assertRaises(TypeError, filterfalse, isEven, 3)
762 self.assertRaises(TypeError, next, filterfalse(range(6), range(6)))
Serhiy Storchakabad12572014-12-15 14:03:42 +0200763 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
764 self.pickletest(proto, filterfalse(isEven, range(6)))
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000765
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000766 def test_zip(self):
767 # XXX This is rather silly now that builtin zip() calls zip()...
768 ans = [(x,y) for x, y in zip('abc',count())]
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000769 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000770 self.assertEqual(list(zip('abc', range(6))), lzip('abc', range(6)))
771 self.assertEqual(list(zip('abcdef', range(3))), lzip('abcdef', range(3)))
772 self.assertEqual(take(3,zip('abcdef', count())), lzip('abcdef', range(3)))
773 self.assertEqual(list(zip('abcdef')), lzip('abcdef'))
774 self.assertEqual(list(zip()), lzip())
775 self.assertRaises(TypeError, zip, 3)
776 self.assertRaises(TypeError, zip, range(3), 3)
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000777 self.assertEqual([tuple(list(pair)) for pair in zip('abc', 'def')],
Guido van Rossum801f0d72006-08-24 19:48:10 +0000778 lzip('abc', 'def'))
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000779 self.assertEqual([pair for pair in zip('abc', 'def')],
Guido van Rossum801f0d72006-08-24 19:48:10 +0000780 lzip('abc', 'def'))
Alex Gaynore151d212011-07-17 16:21:30 -0700781
782 @support.impl_detail("tuple reuse is specific to CPython")
783 def test_zip_tuple_reuse(self):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000784 ids = list(map(id, zip('abc', 'def')))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000785 self.assertEqual(min(ids), max(ids))
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000786 ids = list(map(id, list(zip('abc', 'def'))))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +0000787 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000788
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000789 # check copy, deepcopy, pickle
790 ans = [(x,y) for x, y in copy.copy(zip('abc',count()))]
791 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
792
793 ans = [(x,y) for x, y in copy.deepcopy(zip('abc',count()))]
794 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
795
Serhiy Storchakabad12572014-12-15 14:03:42 +0200796 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
797 ans = [(x,y) for x, y in pickle.loads(pickle.dumps(zip('abc',count()), proto))]
798 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000799
Serhiy Storchakabad12572014-12-15 14:03:42 +0200800 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
801 testIntermediate = zip('abc',count())
802 next(testIntermediate)
803 ans = [(x,y) for x, y in pickle.loads(pickle.dumps(testIntermediate, proto))]
804 self.assertEqual(ans, [('b', 1), ('c', 2)])
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000805
Serhiy Storchakabad12572014-12-15 14:03:42 +0200806 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
807 self.pickletest(proto, zip('abc', count()))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000808
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000809 def test_ziplongest(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000810 for args in [
811 ['abc', range(6)],
812 [range(6), 'abc'],
813 [range(1000), range(2000,2100), range(3000,3050)],
814 [range(1000), range(0), range(3000,3050), range(1200), range(1500)],
815 [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
816 ]:
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000817 target = [tuple([arg[i] if i < len(arg) else None for arg in args])
818 for i in range(max(map(len, args)))]
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000819 self.assertEqual(list(zip_longest(*args)), target)
820 self.assertEqual(list(zip_longest(*args, **{})), target)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000821 target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X'
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000822 self.assertEqual(list(zip_longest(*args, **dict(fillvalue='X'))), target)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000823
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000824 self.assertEqual(take(3,zip_longest('abcdef', count())), list(zip('abcdef', range(3)))) # take 3 from infinite input
Thomas Wouterscf297e42007-02-23 15:07:44 +0000825
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000826 self.assertEqual(list(zip_longest()), list(zip()))
827 self.assertEqual(list(zip_longest([])), list(zip([])))
828 self.assertEqual(list(zip_longest('abcdef')), list(zip('abcdef')))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000829
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000830 self.assertEqual(list(zip_longest('abc', 'defg', **{})),
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000831 list(zip(list('abc')+[None], 'defg'))) # empty keyword dict
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000832 self.assertRaises(TypeError, zip_longest, 3)
833 self.assertRaises(TypeError, zip_longest, range(3), 3)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000834
835 for stmt in [
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000836 "zip_longest('abc', fv=1)",
837 "zip_longest('abc', fillvalue=1, bogus_keyword=None)",
Thomas Wouterscf297e42007-02-23 15:07:44 +0000838 ]:
839 try:
840 eval(stmt, globals(), locals())
841 except TypeError:
842 pass
843 else:
844 self.fail('Did not raise Type in: ' + stmt)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000845
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000846 self.assertEqual([tuple(list(pair)) for pair in zip_longest('abc', 'def')],
Thomas Wouterscf297e42007-02-23 15:07:44 +0000847 list(zip('abc', 'def')))
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000848 self.assertEqual([pair for pair in zip_longest('abc', 'def')],
Thomas Wouterscf297e42007-02-23 15:07:44 +0000849 list(zip('abc', 'def')))
Alex Gaynore151d212011-07-17 16:21:30 -0700850
851 @support.impl_detail("tuple reuse is specific to CPython")
852 def test_zip_longest_tuple_reuse(self):
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000853 ids = list(map(id, zip_longest('abc', 'def')))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000854 self.assertEqual(min(ids), max(ids))
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000855 ids = list(map(id, list(zip_longest('abc', 'def'))))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000856 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
857
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000858 def test_zip_longest_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200859 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
860 self.pickletest(proto, zip_longest("abc", "def"))
861 self.pickletest(proto, zip_longest("abc", "defgh"))
862 self.pickletest(proto, zip_longest("abc", "defgh", fillvalue=1))
863 self.pickletest(proto, zip_longest("", "defgh"))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000864
Raymond Hettingerfc438512009-11-01 20:55:33 +0000865 def test_bug_7244(self):
866
867 class Repeater:
868 # this class is similar to itertools.repeat
869 def __init__(self, o, t, e):
870 self.o = o
871 self.t = int(t)
872 self.e = e
873 def __iter__(self): # its iterator is itself
874 return self
875 def __next__(self):
876 if self.t > 0:
877 self.t -= 1
878 return self.o
879 else:
880 raise self.e
881
882 # Formerly this code in would fail in debug mode
883 # with Undetected Error and Stop Iteration
884 r1 = Repeater(1, 3, StopIteration)
885 r2 = Repeater(2, 4, StopIteration)
886 def run(r1, r2):
887 result = []
888 for i, j in zip_longest(r1, r2, fillvalue=0):
889 with support.captured_output('stdout'):
890 print((i, j))
891 result.append((i, j))
892 return result
893 self.assertEqual(run(r1, r2), [(1,2), (1,2), (1,2), (0,2)])
894
895 # Formerly, the RuntimeError would be lost
896 # and StopIteration would stop as expected
897 r1 = Repeater(1, 3, RuntimeError)
898 r2 = Repeater(2, 4, StopIteration)
899 it = zip_longest(r1, r2, fillvalue=0)
900 self.assertEqual(next(it), (1, 2))
901 self.assertEqual(next(it), (1, 2))
902 self.assertEqual(next(it), (1, 2))
903 self.assertRaises(RuntimeError, next, it)
904
Christian Heimesc3f30c42008-02-22 16:37:40 +0000905 def test_product(self):
906 for args, result in [
Christian Heimes78644762008-03-04 23:39:23 +0000907 ([], [()]), # zero iterables
Christian Heimesc3f30c42008-02-22 16:37:40 +0000908 (['ab'], [('a',), ('b',)]), # one iterable
909 ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables
910 ([range(0), range(2), range(3)], []), # first iterable with zero length
911 ([range(2), range(0), range(3)], []), # middle iterable with zero length
912 ([range(2), range(3), range(0)], []), # last iterable with zero length
913 ]:
914 self.assertEqual(list(product(*args)), result)
Christian Heimesf16baeb2008-02-29 14:57:44 +0000915 for r in range(4):
916 self.assertEqual(list(product(*(args*r))),
917 list(product(*args, **dict(repeat=r))))
Christian Heimesc3f30c42008-02-22 16:37:40 +0000918 self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
919 self.assertRaises(TypeError, product, range(6), None)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000920
921 def product1(*args, **kwds):
922 pools = list(map(tuple, args)) * kwds.get('repeat', 1)
923 n = len(pools)
924 if n == 0:
925 yield ()
926 return
927 if any(len(pool) == 0 for pool in pools):
928 return
929 indices = [0] * n
930 yield tuple(pool[i] for pool, i in zip(pools, indices))
931 while 1:
932 for i in reversed(range(n)): # right to left
933 if indices[i] == len(pools[i]) - 1:
934 continue
935 indices[i] += 1
936 for j in range(i+1, n):
937 indices[j] = 0
938 yield tuple(pool[i] for pool, i in zip(pools, indices))
939 break
940 else:
941 return
942
943 def product2(*args, **kwds):
944 'Pure python version used in docs'
945 pools = list(map(tuple, args)) * kwds.get('repeat', 1)
946 result = [[]]
947 for pool in pools:
948 result = [x+[y] for x in result for y in pool]
949 for prod in result:
950 yield tuple(prod)
951
Christian Heimesc3f30c42008-02-22 16:37:40 +0000952 argtypes = ['', 'abc', '', range(0), range(4), dict(a=1, b=2, c=3),
953 set('abcdefg'), range(11), tuple(range(13))]
954 for i in range(100):
955 args = [random.choice(argtypes) for j in range(random.randrange(5))]
Christian Heimes78644762008-03-04 23:39:23 +0000956 expected_len = prod(map(len, args))
957 self.assertEqual(len(list(product(*args))), expected_len)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000958 self.assertEqual(list(product(*args)), list(product1(*args)))
959 self.assertEqual(list(product(*args)), list(product2(*args)))
Christian Heimesc3f30c42008-02-22 16:37:40 +0000960 args = map(iter, args)
Christian Heimes78644762008-03-04 23:39:23 +0000961 self.assertEqual(len(list(product(*args))), expected_len)
Christian Heimesc3f30c42008-02-22 16:37:40 +0000962
Benjamin Peterson0eaabf12015-02-01 21:34:07 -0500963 @support.bigaddrspacetest
964 def test_product_overflow(self):
Serhiy Storchakadee948b2015-02-03 01:34:09 +0200965 with self.assertRaises((OverflowError, MemoryError)):
966 product(*(['ab']*2**5), repeat=2**25)
Benjamin Peterson0eaabf12015-02-01 21:34:07 -0500967
Alex Gaynore151d212011-07-17 16:21:30 -0700968 @support.impl_detail("tuple reuse is specific to CPython")
969 def test_product_tuple_reuse(self):
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000970 self.assertEqual(len(set(map(id, product('abc', 'def')))), 1)
971 self.assertNotEqual(len(set(map(id, list(product('abc', 'def'))))), 1)
Christian Heimesc3f30c42008-02-22 16:37:40 +0000972
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000973 def test_product_pickling(self):
974 # check copy, deepcopy, pickle
975 for args, result in [
976 ([], [()]), # zero iterables
977 (['ab'], [('a',), ('b',)]), # one iterable
978 ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables
979 ([range(0), range(2), range(3)], []), # first iterable with zero length
980 ([range(2), range(0), range(3)], []), # middle iterable with zero length
981 ([range(2), range(3), range(0)], []), # last iterable with zero length
982 ]:
983 self.assertEqual(list(copy.copy(product(*args))), result)
984 self.assertEqual(list(copy.deepcopy(product(*args))), result)
Serhiy Storchakabad12572014-12-15 14:03:42 +0200985 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
986 self.pickletest(proto, product(*args))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000987
Kristján Valur Jónsson102764a2015-09-12 15:20:54 +0000988 def test_product_issue_25021(self):
989 # test that indices are properly clamped to the length of the tuples
990 p = product((1, 2),(3,))
991 p.__setstate__((0, 0x1000)) # will access tuple element 1 if not clamped
992 self.assertEqual(next(p), (2, 3))
993 # test that empty tuple in the list will result in an immediate StopIteration
994 p = product((1, 2), (), (3,))
995 p.__setstate__((0, 0, 0x1000)) # will access tuple element 1 if not clamped
996 self.assertRaises(StopIteration, next, p)
997
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000998 def test_repeat(self):
Raymond Hettingerf4bb7f22009-02-19 02:44:01 +0000999 self.assertEqual(list(repeat(object='a', times=3)), ['a', 'a', 'a'])
Guido van Rossum805365e2007-05-07 22:24:25 +00001000 self.assertEqual(lzip(range(3),repeat('a')),
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001001 [(0, 'a'), (1, 'a'), (2, 'a')])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +00001002 self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
Raymond Hettinger02420702003-06-29 20:36:23 +00001003 self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00001004 self.assertEqual(list(repeat('a', 0)), [])
1005 self.assertEqual(list(repeat('a', -3)), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001006 self.assertRaises(TypeError, repeat)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00001007 self.assertRaises(TypeError, repeat, None, 3, 4)
1008 self.assertRaises(TypeError, repeat, None, 'a')
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001009 r = repeat(1+0j)
1010 self.assertEqual(repr(r), 'repeat((1+0j))')
1011 r = repeat(1+0j, 5)
1012 self.assertEqual(repr(r), 'repeat((1+0j), 5)')
1013 list(r)
1014 self.assertEqual(repr(r), 'repeat((1+0j), 0)')
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001015
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001016 # check copy, deepcopy, pickle
1017 c = repeat(object='a', times=10)
1018 self.assertEqual(next(c), 'a')
1019 self.assertEqual(take(2, copy.copy(c)), list('a' * 2))
1020 self.assertEqual(take(2, copy.deepcopy(c)), list('a' * 2))
Serhiy Storchakabad12572014-12-15 14:03:42 +02001021 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1022 self.pickletest(proto, repeat(object='a', times=10))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001023
Raymond Hettinger97d35552014-06-24 21:36:58 -07001024 def test_repeat_with_negative_times(self):
1025 self.assertEqual(repr(repeat('a', -1)), "repeat('a', 0)")
1026 self.assertEqual(repr(repeat('a', -2)), "repeat('a', 0)")
1027 self.assertEqual(repr(repeat('a', times=-1)), "repeat('a', 0)")
1028 self.assertEqual(repr(repeat('a', times=-2)), "repeat('a', 0)")
1029
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001030 def test_map(self):
1031 self.assertEqual(list(map(operator.pow, range(3), range(1,7))),
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001032 [0**1, 1**2, 2**3])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001033 self.assertEqual(list(map(tupleize, 'abc', range(5))),
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001034 [('a',0),('b',1),('c',2)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001035 self.assertEqual(list(map(tupleize, 'abc', count())),
Raymond Hettinger02420702003-06-29 20:36:23 +00001036 [('a',0),('b',1),('c',2)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001037 self.assertEqual(take(2,map(tupleize, 'abc', count())),
Raymond Hettinger02420702003-06-29 20:36:23 +00001038 [('a',0),('b',1)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001039 self.assertEqual(list(map(operator.pow, [])), [])
1040 self.assertRaises(TypeError, map)
1041 self.assertRaises(TypeError, list, map(None, range(3), range(3)))
1042 self.assertRaises(TypeError, map, operator.neg)
1043 self.assertRaises(TypeError, next, map(10, range(5)))
1044 self.assertRaises(ValueError, next, map(errfunc, [4], [5]))
1045 self.assertRaises(TypeError, next, map(onearg, [4], [5]))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001046
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001047 # check copy, deepcopy, pickle
1048 ans = [('a',0),('b',1),('c',2)]
1049
1050 c = map(tupleize, 'abc', count())
1051 self.assertEqual(list(copy.copy(c)), ans)
1052
1053 c = map(tupleize, 'abc', count())
1054 self.assertEqual(list(copy.deepcopy(c)), ans)
1055
Serhiy Storchakabad12572014-12-15 14:03:42 +02001056 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1057 c = map(tupleize, 'abc', count())
1058 self.pickletest(proto, c)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001059
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001060 def test_starmap(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001061 self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
1062 [0**1, 1**2, 2**3])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001063 self.assertEqual(take(3, starmap(operator.pow, zip(count(), count(1)))),
Raymond Hettinger02420702003-06-29 20:36:23 +00001064 [0**1, 1**2, 2**3])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00001065 self.assertEqual(list(starmap(operator.pow, [])), [])
Christian Heimes679db4a2008-01-18 09:56:22 +00001066 self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5])
1067 self.assertRaises(TypeError, list, starmap(operator.pow, [None]))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00001068 self.assertRaises(TypeError, starmap)
1069 self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
Georg Brandla18af4e2007-04-21 15:47:16 +00001070 self.assertRaises(TypeError, next, starmap(10, [(4,5)]))
1071 self.assertRaises(ValueError, next, starmap(errfunc, [(4,5)]))
1072 self.assertRaises(TypeError, next, starmap(onearg, [(4,5)]))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001073
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001074 # check copy, deepcopy, pickle
1075 ans = [0**1, 1**2, 2**3]
1076
1077 c = starmap(operator.pow, zip(range(3), range(1,7)))
1078 self.assertEqual(list(copy.copy(c)), ans)
1079
1080 c = starmap(operator.pow, zip(range(3), range(1,7)))
1081 self.assertEqual(list(copy.deepcopy(c)), ans)
1082
Serhiy Storchakabad12572014-12-15 14:03:42 +02001083 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1084 c = starmap(operator.pow, zip(range(3), range(1,7)))
1085 self.pickletest(proto, c)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001086
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001087 def test_islice(self):
1088 for args in [ # islice(args) should agree with range(args)
1089 (10, 20, 3),
1090 (10, 3, 20),
1091 (10, 20),
1092 (10, 3),
1093 (20,)
1094 ]:
Guido van Rossum805365e2007-05-07 22:24:25 +00001095 self.assertEqual(list(islice(range(100), *args)),
1096 list(range(*args)))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001097
1098 for args, tgtargs in [ # Stop when seqn is exhausted
1099 ((10, 110, 3), ((10, 100, 3))),
1100 ((10, 110), ((10, 100))),
1101 ((110,), (100,))
1102 ]:
Guido van Rossum805365e2007-05-07 22:24:25 +00001103 self.assertEqual(list(islice(range(100), *args)),
1104 list(range(*tgtargs)))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001105
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001106 # Test stop=None
Guido van Rossum805365e2007-05-07 22:24:25 +00001107 self.assertEqual(list(islice(range(10), None)), list(range(10)))
1108 self.assertEqual(list(islice(range(10), None, None)), list(range(10)))
1109 self.assertEqual(list(islice(range(10), None, None, None)), list(range(10)))
1110 self.assertEqual(list(islice(range(10), 2, None)), list(range(2, 10)))
1111 self.assertEqual(list(islice(range(10), 1, None, 2)), list(range(1, 10, 2)))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001112
Raymond Hettingerfdf3bd62005-03-27 20:11:44 +00001113 # Test number of items consumed SF #1171417
1114 it = iter(range(10))
Guido van Rossum805365e2007-05-07 22:24:25 +00001115 self.assertEqual(list(islice(it, 3)), list(range(3)))
1116 self.assertEqual(list(it), list(range(3, 10)))
Raymond Hettingerfdf3bd62005-03-27 20:11:44 +00001117
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001118 # Test invalid arguments
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001119 ra = range(10)
1120 self.assertRaises(TypeError, islice, ra)
1121 self.assertRaises(TypeError, islice, ra, 1, 2, 3, 4)
1122 self.assertRaises(ValueError, islice, ra, -5, 10, 1)
1123 self.assertRaises(ValueError, islice, ra, 1, -5, -1)
1124 self.assertRaises(ValueError, islice, ra, 1, 10, -1)
1125 self.assertRaises(ValueError, islice, ra, 1, 10, 0)
1126 self.assertRaises(ValueError, islice, ra, 'a')
1127 self.assertRaises(ValueError, islice, ra, 'a', 1)
1128 self.assertRaises(ValueError, islice, ra, 1, 'a')
1129 self.assertRaises(ValueError, islice, ra, 'a', 1, 1)
1130 self.assertRaises(ValueError, islice, ra, 1, 'a', 1)
Guido van Rossum360e4b82007-05-14 22:51:27 +00001131 self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001132
Raymond Hettinger69b34bf2010-11-30 02:49:29 +00001133 # Issue #10323: Less islice in a predictable state
1134 c = count()
1135 self.assertEqual(list(islice(c, 1, 3, 50)), [1])
1136 self.assertEqual(next(c), 3)
1137
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001138 # check copy, deepcopy, pickle
1139 for args in [ # islice(args) should agree with range(args)
1140 (10, 20, 3),
1141 (10, 3, 20),
1142 (10, 20),
1143 (10, 3),
1144 (20,)
1145 ]:
1146 self.assertEqual(list(copy.copy(islice(range(100), *args))),
1147 list(range(*args)))
1148 self.assertEqual(list(copy.deepcopy(islice(range(100), *args))),
1149 list(range(*args)))
Serhiy Storchakabad12572014-12-15 14:03:42 +02001150 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1151 self.pickletest(proto, islice(range(100), *args))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001152
Antoine Pitrou26f82ef2014-04-29 12:13:46 +02001153 # Issue #21321: check source iterator is not referenced
1154 # from islice() after the latter has been exhausted
1155 it = (x for x in (1, 2))
1156 wr = weakref.ref(it)
1157 it = islice(it, 1)
1158 self.assertIsNotNone(wr())
1159 list(it) # exhaust the iterator
Benjamin Peterson8e163512014-08-24 18:07:28 -05001160 support.gc_collect()
Antoine Pitrou26f82ef2014-04-29 12:13:46 +02001161 self.assertIsNone(wr())
1162
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001163 def test_takewhile(self):
1164 data = [1, 3, 5, 20, 2, 4, 6, 8]
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001165 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00001166 self.assertEqual(list(takewhile(underten, [])), [])
1167 self.assertRaises(TypeError, takewhile)
1168 self.assertRaises(TypeError, takewhile, operator.pow)
1169 self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
Georg Brandla18af4e2007-04-21 15:47:16 +00001170 self.assertRaises(TypeError, next, takewhile(10, [(4,5)]))
1171 self.assertRaises(ValueError, next, takewhile(errfunc, [(4,5)]))
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001172 t = takewhile(bool, [1, 1, 1, 0, 0, 0])
1173 self.assertEqual(list(t), [1, 1, 1])
Georg Brandla18af4e2007-04-21 15:47:16 +00001174 self.assertRaises(StopIteration, next, t)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001175
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001176 # check copy, deepcopy, pickle
1177 self.assertEqual(list(copy.copy(takewhile(underten, data))), [1, 3, 5])
1178 self.assertEqual(list(copy.deepcopy(takewhile(underten, data))),
1179 [1, 3, 5])
Serhiy Storchakabad12572014-12-15 14:03:42 +02001180 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1181 self.pickletest(proto, takewhile(underten, data))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001182
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001183 def test_dropwhile(self):
1184 data = [1, 3, 5, 20, 2, 4, 6, 8]
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001185 self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00001186 self.assertEqual(list(dropwhile(underten, [])), [])
1187 self.assertRaises(TypeError, dropwhile)
1188 self.assertRaises(TypeError, dropwhile, operator.pow)
1189 self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
Georg Brandla18af4e2007-04-21 15:47:16 +00001190 self.assertRaises(TypeError, next, dropwhile(10, [(4,5)]))
1191 self.assertRaises(ValueError, next, dropwhile(errfunc, [(4,5)]))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001192
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001193 # check copy, deepcopy, pickle
1194 self.assertEqual(list(copy.copy(dropwhile(underten, data))), [20, 2, 4, 6, 8])
1195 self.assertEqual(list(copy.deepcopy(dropwhile(underten, data))),
1196 [20, 2, 4, 6, 8])
Serhiy Storchakabad12572014-12-15 14:03:42 +02001197 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1198 self.pickletest(proto, dropwhile(underten, data))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001199
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001200 def test_tee(self):
Raymond Hettingerad983e72003-11-12 14:32:26 +00001201 n = 200
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001202
1203 a, b = tee([]) # test empty iterator
1204 self.assertEqual(list(a), [])
1205 self.assertEqual(list(b), [])
1206
1207 a, b = tee(irange(n)) # test 100% interleaved
Guido van Rossum801f0d72006-08-24 19:48:10 +00001208 self.assertEqual(lzip(a,b), lzip(range(n), range(n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001209
1210 a, b = tee(irange(n)) # test 0% interleaved
Guido van Rossum805365e2007-05-07 22:24:25 +00001211 self.assertEqual(list(a), list(range(n)))
1212 self.assertEqual(list(b), list(range(n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001213
1214 a, b = tee(irange(n)) # test dealloc of leading iterator
Guido van Rossum805365e2007-05-07 22:24:25 +00001215 for i in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +00001216 self.assertEqual(next(a), i)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001217 del a
Guido van Rossum805365e2007-05-07 22:24:25 +00001218 self.assertEqual(list(b), list(range(n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001219
1220 a, b = tee(irange(n)) # test dealloc of trailing iterator
Guido van Rossum805365e2007-05-07 22:24:25 +00001221 for i in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +00001222 self.assertEqual(next(a), i)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001223 del b
Guido van Rossum805365e2007-05-07 22:24:25 +00001224 self.assertEqual(list(a), list(range(100, n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001225
Guido van Rossum805365e2007-05-07 22:24:25 +00001226 for j in range(5): # test randomly interleaved
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001227 order = [0]*n + [1]*n
1228 random.shuffle(order)
1229 lists = ([], [])
1230 its = tee(irange(n))
1231 for i in order:
Georg Brandla18af4e2007-04-21 15:47:16 +00001232 value = next(its[i])
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001233 lists[i].append(value)
Guido van Rossum805365e2007-05-07 22:24:25 +00001234 self.assertEqual(lists[0], list(range(n)))
1235 self.assertEqual(lists[1], list(range(n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001236
Raymond Hettingerad983e72003-11-12 14:32:26 +00001237 # test argument format checking
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001238 self.assertRaises(TypeError, tee)
1239 self.assertRaises(TypeError, tee, 3)
1240 self.assertRaises(TypeError, tee, [1,2], 'x')
Raymond Hettingerad983e72003-11-12 14:32:26 +00001241 self.assertRaises(TypeError, tee, [1,2], 3, 'x')
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001242
Raymond Hettingerad983e72003-11-12 14:32:26 +00001243 # tee object should be instantiable
1244 a, b = tee('abc')
1245 c = type(a)('def')
1246 self.assertEqual(list(c), list('def'))
Raymond Hettingerf0c5aec2003-10-26 14:25:56 +00001247
Raymond Hettingerad983e72003-11-12 14:32:26 +00001248 # test long-lagged and multi-way split
Guido van Rossum805365e2007-05-07 22:24:25 +00001249 a, b, c = tee(range(2000), 3)
1250 for i in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +00001251 self.assertEqual(next(a), i)
Guido van Rossum805365e2007-05-07 22:24:25 +00001252 self.assertEqual(list(b), list(range(2000)))
1253 self.assertEqual([next(c), next(c)], list(range(2)))
1254 self.assertEqual(list(a), list(range(100,2000)))
1255 self.assertEqual(list(c), list(range(2,2000)))
Raymond Hettingerad983e72003-11-12 14:32:26 +00001256
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001257 # test values of n
1258 self.assertRaises(TypeError, tee, 'abc', 'invalid')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001259 self.assertRaises(ValueError, tee, [], -1)
Guido van Rossum805365e2007-05-07 22:24:25 +00001260 for n in range(5):
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001261 result = tee('abc', n)
1262 self.assertEqual(type(result), tuple)
1263 self.assertEqual(len(result), n)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001264 self.assertEqual([list(x) for x in result], [list('abc')]*n)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001265
Raymond Hettingerad983e72003-11-12 14:32:26 +00001266 # tee pass-through to copyable iterator
1267 a, b = tee('abc')
1268 c, d = tee(a)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001269 self.assertTrue(a is c)
Raymond Hettingerad983e72003-11-12 14:32:26 +00001270
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001271 # test tee_new
1272 t1, t2 = tee('abc')
1273 tnew = type(t1)
1274 self.assertRaises(TypeError, tnew)
1275 self.assertRaises(TypeError, tnew, 10)
1276 t3 = tnew(t1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001277 self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc'))
Raymond Hettingerf0c5aec2003-10-26 14:25:56 +00001278
Raymond Hettingera9f60922004-10-17 16:40:14 +00001279 # test that tee objects are weak referencable
Guido van Rossum805365e2007-05-07 22:24:25 +00001280 a, b = tee(range(10))
Antoine Pitrou26f82ef2014-04-29 12:13:46 +02001281 p = weakref.proxy(a)
Raymond Hettingera9f60922004-10-17 16:40:14 +00001282 self.assertEqual(getattr(p, '__class__'), type(b))
1283 del a
1284 self.assertRaises(ReferenceError, getattr, p, '__class__')
1285
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001286 ans = list('abc')
1287 long_ans = list(range(10000))
1288
1289 # check copy
1290 a, b = tee('abc')
1291 self.assertEqual(list(copy.copy(a)), ans)
1292 self.assertEqual(list(copy.copy(b)), ans)
1293 a, b = tee(list(range(10000)))
1294 self.assertEqual(list(copy.copy(a)), long_ans)
1295 self.assertEqual(list(copy.copy(b)), long_ans)
1296
1297 # check partially consumed copy
1298 a, b = tee('abc')
1299 take(2, a)
1300 take(1, b)
1301 self.assertEqual(list(copy.copy(a)), ans[2:])
1302 self.assertEqual(list(copy.copy(b)), ans[1:])
1303 self.assertEqual(list(a), ans[2:])
1304 self.assertEqual(list(b), ans[1:])
1305 a, b = tee(range(10000))
1306 take(100, a)
1307 take(60, b)
1308 self.assertEqual(list(copy.copy(a)), long_ans[100:])
1309 self.assertEqual(list(copy.copy(b)), long_ans[60:])
1310 self.assertEqual(list(a), long_ans[100:])
1311 self.assertEqual(list(b), long_ans[60:])
1312
1313 # check deepcopy
1314 a, b = tee('abc')
1315 self.assertEqual(list(copy.deepcopy(a)), ans)
1316 self.assertEqual(list(copy.deepcopy(b)), ans)
1317 self.assertEqual(list(a), ans)
1318 self.assertEqual(list(b), ans)
1319 a, b = tee(range(10000))
1320 self.assertEqual(list(copy.deepcopy(a)), long_ans)
1321 self.assertEqual(list(copy.deepcopy(b)), long_ans)
1322 self.assertEqual(list(a), long_ans)
1323 self.assertEqual(list(b), long_ans)
1324
1325 # check partially consumed deepcopy
1326 a, b = tee('abc')
1327 take(2, a)
1328 take(1, b)
1329 self.assertEqual(list(copy.deepcopy(a)), ans[2:])
1330 self.assertEqual(list(copy.deepcopy(b)), ans[1:])
1331 self.assertEqual(list(a), ans[2:])
1332 self.assertEqual(list(b), ans[1:])
1333 a, b = tee(range(10000))
1334 take(100, a)
1335 take(60, b)
1336 self.assertEqual(list(copy.deepcopy(a)), long_ans[100:])
1337 self.assertEqual(list(copy.deepcopy(b)), long_ans[60:])
1338 self.assertEqual(list(a), long_ans[100:])
1339 self.assertEqual(list(b), long_ans[60:])
1340
1341 # check pickle
Serhiy Storchakabad12572014-12-15 14:03:42 +02001342 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1343 self.pickletest(proto, iter(tee('abc')))
1344 a, b = tee('abc')
1345 self.pickletest(proto, a, compare=ans)
1346 self.pickletest(proto, b, compare=ans)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001347
Serhiy Storchakaa3e91282013-01-25 13:19:31 +02001348 # Issue 13454: Crash when deleting backward iterator from tee()
1349 def test_tee_del_backward(self):
Serhiy Storchaka5bb893c2013-01-26 11:52:06 +02001350 forward, backward = tee(repeat(None, 20000000))
Serhiy Storchaka9db55002015-03-28 20:38:37 +02001351 try:
1352 any(forward) # exhaust the iterator
1353 del backward
1354 except:
1355 del forward, backward
1356 raise
Serhiy Storchakaa3e91282013-01-25 13:19:31 +02001357
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001358 def test_StopIteration(self):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001359 self.assertRaises(StopIteration, next, zip())
Raymond Hettingerb5a42082003-08-08 05:10:41 +00001360
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001361 for f in (chain, cycle, zip, groupby):
Georg Brandla18af4e2007-04-21 15:47:16 +00001362 self.assertRaises(StopIteration, next, f([]))
1363 self.assertRaises(StopIteration, next, f(StopNow()))
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001364
Georg Brandla18af4e2007-04-21 15:47:16 +00001365 self.assertRaises(StopIteration, next, islice([], None))
1366 self.assertRaises(StopIteration, next, islice(StopNow(), None))
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001367
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001368 p, q = tee([])
Georg Brandla18af4e2007-04-21 15:47:16 +00001369 self.assertRaises(StopIteration, next, p)
1370 self.assertRaises(StopIteration, next, q)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001371 p, q = tee(StopNow())
Georg Brandla18af4e2007-04-21 15:47:16 +00001372 self.assertRaises(StopIteration, next, p)
1373 self.assertRaises(StopIteration, next, q)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001374
Georg Brandla18af4e2007-04-21 15:47:16 +00001375 self.assertRaises(StopIteration, next, repeat(None, 0))
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001376
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001377 for f in (filter, filterfalse, map, takewhile, dropwhile, starmap):
Georg Brandla18af4e2007-04-21 15:47:16 +00001378 self.assertRaises(StopIteration, next, f(lambda x:x, []))
1379 self.assertRaises(StopIteration, next, f(lambda x:x, StopNow()))
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001380
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001381class TestExamples(unittest.TestCase):
1382
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001383 def test_accumulate(self):
Raymond Hettinger482ba772010-12-01 22:48:00 +00001384 self.assertEqual(list(accumulate([1,2,3,4,5])), [1, 3, 6, 10, 15])
1385
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001386 def test_accumulate_reducible(self):
1387 # check copy, deepcopy, pickle
1388 data = [1, 2, 3, 4, 5]
1389 accumulated = [1, 3, 6, 10, 15]
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001390
Serhiy Storchakabad12572014-12-15 14:03:42 +02001391 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1392 it = accumulate(data)
1393 self.assertEqual(list(pickle.loads(pickle.dumps(it, proto))), accumulated[:])
1394 self.assertEqual(next(it), 1)
1395 self.assertEqual(list(pickle.loads(pickle.dumps(it, proto))), accumulated[1:])
1396 it = accumulate(data)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001397 self.assertEqual(next(it), 1)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001398 self.assertEqual(list(copy.deepcopy(it)), accumulated[1:])
1399 self.assertEqual(list(copy.copy(it)), accumulated[1:])
1400
Serhiy Storchakad5516252016-03-06 14:00:45 +02001401 def test_accumulate_reducible_none(self):
1402 # Issue #25718: total is None
1403 it = accumulate([None, None, None], operator.is_)
1404 self.assertEqual(next(it), None)
1405 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1406 it_copy = pickle.loads(pickle.dumps(it, proto))
1407 self.assertEqual(list(it_copy), [True, False])
1408 self.assertEqual(list(copy.deepcopy(it)), [True, False])
1409 self.assertEqual(list(copy.copy(it)), [True, False])
1410
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001411 def test_chain(self):
1412 self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF')
1413
1414 def test_chain_from_iterable(self):
1415 self.assertEqual(''.join(chain.from_iterable(['ABC', 'DEF'])), 'ABCDEF')
1416
1417 def test_combinations(self):
1418 self.assertEqual(list(combinations('ABCD', 2)),
1419 [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
1420 self.assertEqual(list(combinations(range(4), 3)),
1421 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
1422
Raymond Hettingerd07d9392009-01-27 04:20:44 +00001423 def test_combinations_with_replacement(self):
1424 self.assertEqual(list(combinations_with_replacement('ABC', 2)),
1425 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
1426
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +00001427 def test_compress(self):
1428 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
1429
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001430 def test_count(self):
1431 self.assertEqual(list(islice(count(10), 5)), [10, 11, 12, 13, 14])
1432
1433 def test_cycle(self):
1434 self.assertEqual(list(islice(cycle('ABCD'), 12)), list('ABCDABCDABCD'))
1435
1436 def test_dropwhile(self):
1437 self.assertEqual(list(dropwhile(lambda x: x<5, [1,4,6,4,1])), [6,4,1])
1438
1439 def test_groupby(self):
1440 self.assertEqual([k for k, g in groupby('AAAABBBCCDAABBB')],
1441 list('ABCDAB'))
1442 self.assertEqual([(list(g)) for k, g in groupby('AAAABBBCCD')],
1443 [list('AAAA'), list('BBB'), list('CC'), list('D')])
1444
1445 def test_filter(self):
1446 self.assertEqual(list(filter(lambda x: x%2, range(10))), [1,3,5,7,9])
1447
1448 def test_filterfalse(self):
1449 self.assertEqual(list(filterfalse(lambda x: x%2, range(10))), [0,2,4,6,8])
1450
1451 def test_map(self):
1452 self.assertEqual(list(map(pow, (2,3,10), (5,2,3))), [32, 9, 1000])
1453
1454 def test_islice(self):
1455 self.assertEqual(list(islice('ABCDEFG', 2)), list('AB'))
1456 self.assertEqual(list(islice('ABCDEFG', 2, 4)), list('CD'))
1457 self.assertEqual(list(islice('ABCDEFG', 2, None)), list('CDEFG'))
1458 self.assertEqual(list(islice('ABCDEFG', 0, None, 2)), list('ACEG'))
1459
1460 def test_zip(self):
1461 self.assertEqual(list(zip('ABCD', 'xy')), [('A', 'x'), ('B', 'y')])
1462
1463 def test_zip_longest(self):
1464 self.assertEqual(list(zip_longest('ABCD', 'xy', fillvalue='-')),
1465 [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')])
1466
1467 def test_permutations(self):
1468 self.assertEqual(list(permutations('ABCD', 2)),
1469 list(map(tuple, 'AB AC AD BA BC BD CA CB CD DA DB DC'.split())))
1470 self.assertEqual(list(permutations(range(3))),
1471 [(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0)])
1472
1473 def test_product(self):
1474 self.assertEqual(list(product('ABCD', 'xy')),
1475 list(map(tuple, 'Ax Ay Bx By Cx Cy Dx Dy'.split())))
1476 self.assertEqual(list(product(range(2), repeat=3)),
1477 [(0,0,0), (0,0,1), (0,1,0), (0,1,1),
1478 (1,0,0), (1,0,1), (1,1,0), (1,1,1)])
1479
1480 def test_repeat(self):
1481 self.assertEqual(list(repeat(10, 3)), [10, 10, 10])
1482
1483 def test_stapmap(self):
1484 self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])),
1485 [32, 9, 1000])
1486
1487 def test_takewhile(self):
1488 self.assertEqual(list(takewhile(lambda x: x<5, [1,4,6,4,1])), [1,4])
1489
1490
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001491class TestGC(unittest.TestCase):
1492
1493 def makecycle(self, iterator, container):
1494 container.append(iterator)
Georg Brandla18af4e2007-04-21 15:47:16 +00001495 next(iterator)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001496 del container, iterator
1497
Raymond Hettinger482ba772010-12-01 22:48:00 +00001498 def test_accumulate(self):
1499 a = []
1500 self.makecycle(accumulate([1,2,a,3]), a)
1501
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001502 def test_chain(self):
1503 a = []
1504 self.makecycle(chain(a), a)
1505
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001506 def test_chain_from_iterable(self):
1507 a = []
1508 self.makecycle(chain.from_iterable([a]), a)
1509
1510 def test_combinations(self):
1511 a = []
1512 self.makecycle(combinations([1,2,a,3], 3), a)
1513
Raymond Hettingerd07d9392009-01-27 04:20:44 +00001514 def test_combinations_with_replacement(self):
1515 a = []
1516 self.makecycle(combinations_with_replacement([1,2,a,3], 3), a)
1517
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +00001518 def test_compress(self):
1519 a = []
1520 self.makecycle(compress('ABCDEF', [1,0,1,0,1,0]), a)
1521
Raymond Hettingerd6280f42009-02-16 20:50:56 +00001522 def test_count(self):
1523 a = []
1524 Int = type('Int', (int,), dict(x=a))
1525 self.makecycle(count(Int(0), Int(1)), a)
1526
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001527 def test_cycle(self):
1528 a = []
1529 self.makecycle(cycle([a]*2), a)
1530
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001531 def test_dropwhile(self):
1532 a = []
1533 self.makecycle(dropwhile(bool, [0, a, a]), a)
1534
1535 def test_groupby(self):
1536 a = []
1537 self.makecycle(groupby([a]*2, lambda x:x), a)
1538
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001539 def test_issue2246(self):
1540 # Issue 2246 -- the _grouper iterator was not included in GC
1541 n = 10
1542 keyfunc = lambda x: x
1543 for i, j in groupby(range(n), key=keyfunc):
1544 keyfunc.__dict__.setdefault('x',[]).append(j)
1545
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001546 def test_filter(self):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001547 a = []
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001548 self.makecycle(filter(lambda x:True, [a]*2), a)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001549
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001550 def test_filterfalse(self):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001551 a = []
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001552 self.makecycle(filterfalse(lambda x:False, a), a)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001553
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001554 def test_zip(self):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001555 a = []
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001556 self.makecycle(zip([a]*2, [a]*3), a)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001557
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001558 def test_zip_longest(self):
1559 a = []
1560 self.makecycle(zip_longest([a]*2, [a]*3), a)
1561 b = [a, None]
1562 self.makecycle(zip_longest([a]*2, [a]*3, fillvalue=b), a)
1563
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001564 def test_map(self):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001565 a = []
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001566 self.makecycle(map(lambda x:x, [a]*2), a)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001567
1568 def test_islice(self):
1569 a = []
1570 self.makecycle(islice([a]*2, None), a)
1571
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001572 def test_permutations(self):
1573 a = []
1574 self.makecycle(permutations([1,2,a,3], 3), a)
1575
1576 def test_product(self):
1577 a = []
1578 self.makecycle(product([1,2,a,3], repeat=3), a)
1579
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001580 def test_repeat(self):
1581 a = []
1582 self.makecycle(repeat(a), a)
1583
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001584 def test_starmap(self):
1585 a = []
1586 self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)
1587
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001588 def test_takewhile(self):
1589 a = []
1590 self.makecycle(takewhile(bool, [1, 0, a, a]), a)
1591
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001592def R(seqn):
1593 'Regular generator'
1594 for i in seqn:
1595 yield i
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001596
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001597class G:
1598 'Sequence using __getitem__'
1599 def __init__(self, seqn):
1600 self.seqn = seqn
1601 def __getitem__(self, i):
1602 return self.seqn[i]
1603
1604class I:
1605 'Sequence using iterator protocol'
1606 def __init__(self, seqn):
1607 self.seqn = seqn
1608 self.i = 0
1609 def __iter__(self):
1610 return self
Georg Brandla18af4e2007-04-21 15:47:16 +00001611 def __next__(self):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001612 if self.i >= len(self.seqn): raise StopIteration
1613 v = self.seqn[self.i]
1614 self.i += 1
1615 return v
1616
1617class Ig:
1618 'Sequence using iterator protocol defined with a generator'
1619 def __init__(self, seqn):
1620 self.seqn = seqn
1621 self.i = 0
1622 def __iter__(self):
1623 for val in self.seqn:
1624 yield val
1625
1626class X:
1627 'Missing __getitem__ and __iter__'
1628 def __init__(self, seqn):
1629 self.seqn = seqn
1630 self.i = 0
Georg Brandla18af4e2007-04-21 15:47:16 +00001631 def __next__(self):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001632 if self.i >= len(self.seqn): raise StopIteration
1633 v = self.seqn[self.i]
1634 self.i += 1
1635 return v
1636
1637class N:
Georg Brandla18af4e2007-04-21 15:47:16 +00001638 'Iterator missing __next__()'
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001639 def __init__(self, seqn):
1640 self.seqn = seqn
1641 self.i = 0
1642 def __iter__(self):
1643 return self
1644
1645class E:
1646 'Test propagation of exceptions'
1647 def __init__(self, seqn):
1648 self.seqn = seqn
1649 self.i = 0
1650 def __iter__(self):
1651 return self
Georg Brandla18af4e2007-04-21 15:47:16 +00001652 def __next__(self):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +00001653 3 // 0
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001654
1655class S:
1656 'Test immediate stop'
1657 def __init__(self, seqn):
1658 pass
1659 def __iter__(self):
1660 return self
Georg Brandla18af4e2007-04-21 15:47:16 +00001661 def __next__(self):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001662 raise StopIteration
1663
1664def L(seqn):
1665 'Test multiple tiers of iterators'
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001666 return chain(map(lambda x:x, R(Ig(G(seqn)))))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001667
1668
1669class TestVariousIteratorArgs(unittest.TestCase):
1670
Raymond Hettinger482ba772010-12-01 22:48:00 +00001671 def test_accumulate(self):
1672 s = [1,2,3,4,5]
1673 r = [1,3,6,10,15]
1674 n = len(s)
1675 for g in (G, I, Ig, L, R):
1676 self.assertEqual(list(accumulate(g(s))), r)
1677 self.assertEqual(list(accumulate(S(s))), [])
1678 self.assertRaises(TypeError, accumulate, X(s))
1679 self.assertRaises(TypeError, accumulate, N(s))
1680 self.assertRaises(ZeroDivisionError, list, accumulate(E(s)))
1681
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001682 def test_chain(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001683 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001684 for g in (G, I, Ig, S, L, R):
1685 self.assertEqual(list(chain(g(s))), list(g(s)))
1686 self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
Christian Heimesf16baeb2008-02-29 14:57:44 +00001687 self.assertRaises(TypeError, list, chain(X(s)))
Mark Dickinson26a96fa2008-03-01 02:27:46 +00001688 self.assertRaises(TypeError, list, chain(N(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001689 self.assertRaises(ZeroDivisionError, list, chain(E(s)))
1690
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +00001691 def test_compress(self):
1692 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
1693 n = len(s)
1694 for g in (G, I, Ig, S, L, R):
1695 self.assertEqual(list(compress(g(s), repeat(1))), list(g(s)))
1696 self.assertRaises(TypeError, compress, X(s), repeat(1))
1697 self.assertRaises(TypeError, compress, N(s), repeat(1))
1698 self.assertRaises(ZeroDivisionError, list, compress(E(s), repeat(1)))
1699
Christian Heimesc3f30c42008-02-22 16:37:40 +00001700 def test_product(self):
1701 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
1702 self.assertRaises(TypeError, product, X(s))
1703 self.assertRaises(TypeError, product, N(s))
1704 self.assertRaises(ZeroDivisionError, product, E(s))
1705
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001706 def test_cycle(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001707 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001708 for g in (G, I, Ig, S, L, R):
1709 tgtlen = len(s) * 3
1710 expected = list(g(s))*3
1711 actual = list(islice(cycle(g(s)), tgtlen))
1712 self.assertEqual(actual, expected)
1713 self.assertRaises(TypeError, cycle, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001714 self.assertRaises(TypeError, cycle, N(s))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001715 self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
1716
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001717 def test_groupby(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001718 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001719 for g in (G, I, Ig, S, L, R):
1720 self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
1721 self.assertRaises(TypeError, groupby, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001722 self.assertRaises(TypeError, groupby, N(s))
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001723 self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
1724
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001725 def test_filter(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001726 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001727 for g in (G, I, Ig, S, L, R):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001728 self.assertEqual(list(filter(isEven, g(s))),
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001729 [x for x in g(s) if isEven(x)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001730 self.assertRaises(TypeError, filter, isEven, X(s))
1731 self.assertRaises(TypeError, filter, isEven, N(s))
1732 self.assertRaises(ZeroDivisionError, list, filter(isEven, E(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001733
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001734 def test_filterfalse(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001735 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001736 for g in (G, I, Ig, S, L, R):
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001737 self.assertEqual(list(filterfalse(isEven, g(s))),
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001738 [x for x in g(s) if isOdd(x)])
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001739 self.assertRaises(TypeError, filterfalse, isEven, X(s))
1740 self.assertRaises(TypeError, filterfalse, isEven, N(s))
1741 self.assertRaises(ZeroDivisionError, list, filterfalse(isEven, E(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001742
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001743 def test_zip(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001744 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001745 for g in (G, I, Ig, S, L, R):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001746 self.assertEqual(list(zip(g(s))), lzip(g(s)))
1747 self.assertEqual(list(zip(g(s), g(s))), lzip(g(s), g(s)))
1748 self.assertRaises(TypeError, zip, X(s))
1749 self.assertRaises(TypeError, zip, N(s))
1750 self.assertRaises(ZeroDivisionError, list, zip(E(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001751
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001752 def test_ziplongest(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001753 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001754 for g in (G, I, Ig, S, L, R):
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001755 self.assertEqual(list(zip_longest(g(s))), list(zip(g(s))))
1756 self.assertEqual(list(zip_longest(g(s), g(s))), list(zip(g(s), g(s))))
1757 self.assertRaises(TypeError, zip_longest, X(s))
1758 self.assertRaises(TypeError, zip_longest, N(s))
1759 self.assertRaises(ZeroDivisionError, list, zip_longest(E(s)))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001760
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001761 def test_map(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001762 for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001763 for g in (G, I, Ig, S, L, R):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001764 self.assertEqual(list(map(onearg, g(s))),
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001765 [onearg(x) for x in g(s)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001766 self.assertEqual(list(map(operator.pow, g(s), g(s))),
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001767 [x**x for x in g(s)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001768 self.assertRaises(TypeError, map, onearg, X(s))
1769 self.assertRaises(TypeError, map, onearg, N(s))
1770 self.assertRaises(ZeroDivisionError, list, map(onearg, E(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001771
1772 def test_islice(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001773 for s in ("12345", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001774 for g in (G, I, Ig, S, L, R):
1775 self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
1776 self.assertRaises(TypeError, islice, X(s), 10)
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001777 self.assertRaises(TypeError, islice, N(s), 10)
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001778 self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
1779
1780 def test_starmap(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001781 for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001782 for g in (G, I, Ig, S, L, R):
Guido van Rossum801f0d72006-08-24 19:48:10 +00001783 ss = lzip(s, s)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001784 self.assertEqual(list(starmap(operator.pow, g(ss))),
1785 [x**x for x in g(s)])
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001786 self.assertRaises(TypeError, starmap, operator.pow, X(ss))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001787 self.assertRaises(TypeError, starmap, operator.pow, N(ss))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001788 self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
1789
1790 def test_takewhile(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001791 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001792 for g in (G, I, Ig, S, L, R):
1793 tgt = []
1794 for elem in g(s):
1795 if not isEven(elem): break
1796 tgt.append(elem)
1797 self.assertEqual(list(takewhile(isEven, g(s))), tgt)
1798 self.assertRaises(TypeError, takewhile, isEven, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001799 self.assertRaises(TypeError, takewhile, isEven, N(s))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001800 self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
1801
1802 def test_dropwhile(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001803 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001804 for g in (G, I, Ig, S, L, R):
1805 tgt = []
1806 for elem in g(s):
1807 if not tgt and isOdd(elem): continue
1808 tgt.append(elem)
1809 self.assertEqual(list(dropwhile(isOdd, g(s))), tgt)
1810 self.assertRaises(TypeError, dropwhile, isOdd, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001811 self.assertRaises(TypeError, dropwhile, isOdd, N(s))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001812 self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
1813
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001814 def test_tee(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001815 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001816 for g in (G, I, Ig, S, L, R):
1817 it1, it2 = tee(g(s))
1818 self.assertEqual(list(it1), list(g(s)))
1819 self.assertEqual(list(it2), list(g(s)))
1820 self.assertRaises(TypeError, tee, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001821 self.assertRaises(TypeError, tee, N(s))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001822 self.assertRaises(ZeroDivisionError, list, tee(E(s))[0])
1823
Raymond Hettinger5cab2e32004-02-10 09:25:40 +00001824class LengthTransparency(unittest.TestCase):
1825
1826 def test_repeat(self):
Armin Ronacheraa9a79d2012-10-06 14:03:24 +02001827 self.assertEqual(operator.length_hint(repeat(None, 50)), 50)
Raymond Hettinger97d35552014-06-24 21:36:58 -07001828 self.assertEqual(operator.length_hint(repeat(None, 0)), 0)
Armin Ronacheraa9a79d2012-10-06 14:03:24 +02001829 self.assertEqual(operator.length_hint(repeat(None), 12), 12)
Raymond Hettinger5cab2e32004-02-10 09:25:40 +00001830
Raymond Hettinger97d35552014-06-24 21:36:58 -07001831 def test_repeat_with_negative_times(self):
1832 self.assertEqual(operator.length_hint(repeat(None, -1)), 0)
1833 self.assertEqual(operator.length_hint(repeat(None, -2)), 0)
1834 self.assertEqual(operator.length_hint(repeat(None, times=-1)), 0)
1835 self.assertEqual(operator.length_hint(repeat(None, times=-2)), 0)
1836
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001837class RegressionTests(unittest.TestCase):
1838
1839 def test_sf_793826(self):
1840 # Fix Armin Rigo's successful efforts to wreak havoc
1841
1842 def mutatingtuple(tuple1, f, tuple2):
1843 # this builds a tuple t which is a copy of tuple1,
1844 # then calls f(t), then mutates t to be equal to tuple2
1845 # (needs len(tuple1) == len(tuple2)).
1846 def g(value, first=[1]):
1847 if first:
1848 del first[:]
Georg Brandla18af4e2007-04-21 15:47:16 +00001849 f(next(z))
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001850 return value
1851 items = list(tuple2)
1852 items[1:1] = list(tuple1)
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001853 gen = map(g, items)
1854 z = zip(*[gen]*len(tuple1))
Georg Brandla18af4e2007-04-21 15:47:16 +00001855 next(z)
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001856
1857 def f(t):
1858 global T
1859 T = t
1860 first[:] = list(T)
1861
1862 first = []
1863 mutatingtuple((1,2,3), f, (4,5,6))
1864 second = list(T)
1865 self.assertEqual(first, second)
1866
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001867
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001868 def test_sf_950057(self):
1869 # Make sure that chain() and cycle() catch exceptions immediately
1870 # rather than when shifting between input sources
1871
1872 def gen1():
1873 hist.append(0)
1874 yield 1
1875 hist.append(1)
Tim Petersbeb7c0c2004-07-18 17:34:03 +00001876 raise AssertionError
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001877 hist.append(2)
1878
1879 def gen2(x):
1880 hist.append(3)
1881 yield 2
1882 hist.append(4)
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001883
1884 hist = []
1885 self.assertRaises(AssertionError, list, chain(gen1(), gen2(False)))
1886 self.assertEqual(hist, [0,1])
1887
1888 hist = []
1889 self.assertRaises(AssertionError, list, chain(gen1(), gen2(True)))
1890 self.assertEqual(hist, [0,1])
1891
1892 hist = []
1893 self.assertRaises(AssertionError, list, cycle(gen1()))
1894 self.assertEqual(hist, [0,1])
1895
Thomas Woutersb2137042007-02-01 18:02:27 +00001896class SubclassWithKwargsTest(unittest.TestCase):
1897 def test_keywords_in_subclass(self):
1898 # count is not subclassable...
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001899 for cls in (repeat, zip, filter, filterfalse, chain, map,
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +00001900 starmap, islice, takewhile, dropwhile, cycle, compress):
Thomas Woutersb2137042007-02-01 18:02:27 +00001901 class Subclass(cls):
1902 def __init__(self, newarg=None, *args):
1903 cls.__init__(self, *args)
1904 try:
1905 Subclass(newarg=1)
1906 except TypeError as err:
1907 # we expect type errors because of wrong argument count
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001908 self.assertNotIn("does not take keyword arguments", err.args[0])
Thomas Woutersb2137042007-02-01 18:02:27 +00001909
Serhiy Storchaka2dae92a2013-12-09 17:45:57 +02001910@support.cpython_only
1911class SizeofTest(unittest.TestCase):
1912 def setUp(self):
1913 self.ssize_t = struct.calcsize('n')
1914
1915 check_sizeof = support.check_sizeof
1916
1917 def test_product_sizeof(self):
1918 basesize = support.calcobjsize('3Pi')
1919 check = self.check_sizeof
1920 check(product('ab', '12'), basesize + 2 * self.ssize_t)
1921 check(product(*(('abc',) * 10)), basesize + 10 * self.ssize_t)
1922
1923 def test_combinations_sizeof(self):
1924 basesize = support.calcobjsize('3Pni')
1925 check = self.check_sizeof
1926 check(combinations('abcd', 3), basesize + 3 * self.ssize_t)
1927 check(combinations(range(10), 4), basesize + 4 * self.ssize_t)
1928
1929 def test_combinations_with_replacement_sizeof(self):
1930 cwr = combinations_with_replacement
1931 basesize = support.calcobjsize('3Pni')
1932 check = self.check_sizeof
1933 check(cwr('abcd', 3), basesize + 3 * self.ssize_t)
1934 check(cwr(range(10), 4), basesize + 4 * self.ssize_t)
1935
1936 def test_permutations_sizeof(self):
1937 basesize = support.calcobjsize('4Pni')
1938 check = self.check_sizeof
1939 check(permutations('abcd'),
1940 basesize + 4 * self.ssize_t + 4 * self.ssize_t)
1941 check(permutations('abcd', 3),
1942 basesize + 4 * self.ssize_t + 3 * self.ssize_t)
1943 check(permutations('abcde', 3),
1944 basesize + 5 * self.ssize_t + 3 * self.ssize_t)
1945 check(permutations(range(10), 4),
1946 basesize + 10 * self.ssize_t + 4 * self.ssize_t)
1947
Thomas Woutersb2137042007-02-01 18:02:27 +00001948
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001949libreftest = """ Doctest for examples in the library reference: libitertools.tex
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001950
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001951
1952>>> amounts = [120.15, 764.05, 823.14]
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001953>>> for checknum, amount in zip(count(1200), amounts):
Guido van Rossum7131f842007-02-09 20:13:25 +00001954... print('Check %d is for $%.2f' % (checknum, amount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001955...
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001956Check 1200 is for $120.15
1957Check 1201 is for $764.05
1958Check 1202 is for $823.14
1959
1960>>> import operator
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001961>>> for cube in map(operator.pow, range(1,4), repeat(3)):
Guido van Rossum7131f842007-02-09 20:13:25 +00001962... print(cube)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001963...
Raymond Hettinger96ef8112003-02-01 00:10:11 +000019641
19658
196627
1967
1968>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
Raymond Hettinger3567a872003-06-28 05:44:36 +00001969>>> for name in islice(reportlines, 3, None, 2):
Guido van Rossum7131f842007-02-09 20:13:25 +00001970... print(name.title())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001971...
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001972Alex
1973Laura
1974Martin
1975Walter
1976Samuele
1977
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001978>>> from operator import itemgetter
1979>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001980>>> di = sorted(sorted(d.items()), key=itemgetter(1))
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001981>>> for k, g in groupby(di, itemgetter(1)):
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001982... print(k, list(map(itemgetter(0), g)))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001983...
Raymond Hettingerd25c1c62003-12-06 16:23:06 +000019841 ['a', 'c', 'e']
19852 ['b', 'd', 'f']
19863 ['g']
1987
Raymond Hettinger734fb572004-01-20 20:04:40 +00001988# Find runs of consecutive numbers using groupby. The key to the solution
1989# is differencing with a range so that consecutive numbers all appear in
1990# same group.
1991>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001992>>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001993... print(list(map(operator.itemgetter(1), g)))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001994...
Raymond Hettinger734fb572004-01-20 20:04:40 +00001995[1]
1996[4, 5, 6]
1997[10]
1998[15, 16, 17, 18]
1999[22]
2000[25, 26, 27, 28]
2001
Georg Brandl3dbca812008-07-23 16:10:53 +00002002>>> def take(n, iterable):
2003... "Return first n items of the iterable as a list"
2004... return list(islice(iterable, n))
Raymond Hettingera098b332003-09-08 23:58:40 +00002005
Georg Brandl3dbca812008-07-23 16:10:53 +00002006>>> def enumerate(iterable, start=0):
2007... return zip(count(start), iterable)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002008
Georg Brandl3dbca812008-07-23 16:10:53 +00002009>>> def tabulate(function, start=0):
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002010... "Return function(0), function(1), ..."
Georg Brandl3dbca812008-07-23 16:10:53 +00002011... return map(function, count(start))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002012
Raymond Hettingercdf8ba32009-02-19 04:45:07 +00002013>>> def nth(iterable, n, default=None):
2014... "Returns the nth item or a default value"
2015... return next(islice(iterable, n, None), default)
Raymond Hettinger60eca932003-02-09 06:40:58 +00002016
Raymond Hettingere525ee32016-03-06 18:11:38 -08002017>>> def all_equal(iterable):
2018... "Returns True if all the elements are equal to each other"
2019... g = groupby(iterable)
2020... return next(g, True) and not next(g, False)
2021
Georg Brandl3dbca812008-07-23 16:10:53 +00002022>>> def quantify(iterable, pred=bool):
2023... "Count how many times the predicate is true"
2024... return sum(map(pred, iterable))
Raymond Hettinger60eca932003-02-09 06:40:58 +00002025
Georg Brandl3dbca812008-07-23 16:10:53 +00002026>>> def padnone(iterable):
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002027... "Returns the sequence elements and then returns None indefinitely"
Georg Brandl3dbca812008-07-23 16:10:53 +00002028... return chain(iterable, repeat(None))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002029
Georg Brandl3dbca812008-07-23 16:10:53 +00002030>>> def ncycles(iterable, n):
Ezio Melotti13925002011-03-16 11:05:33 +02002031... "Returns the sequence elements n times"
Georg Brandl3dbca812008-07-23 16:10:53 +00002032... return chain(*repeat(iterable, n))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002033
2034>>> def dotproduct(vec1, vec2):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002035... return sum(map(operator.mul, vec1, vec2))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002036
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00002037>>> def flatten(listOfLists):
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002038... return list(chain.from_iterable(listOfLists))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00002039
2040>>> def repeatfunc(func, times=None, *args):
2041... "Repeat calls to func with specified arguments."
2042... " Example: repeatfunc(random.random)"
2043... if times is None:
2044... return starmap(func, repeat(args))
2045... else:
2046... return starmap(func, repeat(args, times))
2047
Raymond Hettingerd591f662003-10-26 15:34:50 +00002048>>> def pairwise(iterable):
2049... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
2050... a, b = tee(iterable)
Raymond Hettingerad983e72003-11-12 14:32:26 +00002051... try:
Georg Brandla18af4e2007-04-21 15:47:16 +00002052... next(b)
Raymond Hettingerad983e72003-11-12 14:32:26 +00002053... except StopIteration:
2054... pass
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002055... return zip(a, b)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002056
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002057>>> def grouper(n, iterable, fillvalue=None):
Raymond Hettingerf5a2e472008-07-30 07:37:37 +00002058... "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002059... args = [iter(iterable)] * n
Raymond Hettinger883d2762009-01-27 04:57:51 +00002060... return zip_longest(*args, fillvalue=fillvalue)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002061
2062>>> def roundrobin(*iterables):
Raymond Hettingerf5a2e472008-07-30 07:37:37 +00002063... "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002064... # Recipe credited to George Sakkis
2065... pending = len(iterables)
2066... nexts = cycle(iter(it).__next__ for it in iterables)
2067... while pending:
2068... try:
2069... for next in nexts:
2070... yield next()
2071... except StopIteration:
2072... pending -= 1
2073... nexts = cycle(islice(nexts, pending))
2074
2075>>> def powerset(iterable):
Raymond Hettingerace67332009-01-26 02:23:50 +00002076... "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
2077... s = list(iterable)
2078... return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002079
Raymond Hettingerad9d96b2009-01-02 21:39:07 +00002080>>> def unique_everseen(iterable, key=None):
2081... "List unique elements, preserving order. Remember all elements ever seen."
2082... # unique_everseen('AAAABBBCCDAABBB') --> A B C D
2083... # unique_everseen('ABBCcAD', str.lower) --> A B C D
2084... seen = set()
2085... seen_add = seen.add
2086... if key is None:
2087... for element in iterable:
2088... if element not in seen:
2089... seen_add(element)
2090... yield element
2091... else:
2092... for element in iterable:
2093... k = key(element)
2094... if k not in seen:
2095... seen_add(k)
2096... yield element
2097
2098>>> def unique_justseen(iterable, key=None):
2099... "List unique elements, preserving order. Remember only the element just seen."
2100... # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
2101... # unique_justseen('ABBCcAD', str.lower) --> A B C A D
2102... return map(next, map(itemgetter(1), groupby(iterable, key)))
2103
Raymond Hettinger31b26f62014-04-02 03:16:42 -07002104>>> def first_true(iterable, default=False, pred=None):
2105... '''Returns the first true value in the iterable.
2106...
2107... If no true value is found, returns *default*
2108...
2109... If *pred* is not None, returns the first item
2110... for which pred(item) is true.
2111...
2112... '''
2113... # first_true([a,b,c], x) --> a or b or c or x
2114... # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
2115... return next(filter(pred, iterable), default)
2116
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002117This is not part of the examples but it tests to make sure the definitions
2118perform as purported.
2119
Raymond Hettingera098b332003-09-08 23:58:40 +00002120>>> take(10, count())
2121[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2122
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002123>>> list(enumerate('abc'))
2124[(0, 'a'), (1, 'b'), (2, 'c')]
2125
2126>>> list(islice(tabulate(lambda x: 2*x), 4))
2127[0, 2, 4, 6]
2128
2129>>> nth('abcde', 3)
Raymond Hettingerd04fa312009-02-04 19:45:13 +00002130'd'
2131
2132>>> nth('abcde', 9) is None
2133True
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002134
Raymond Hettingere525ee32016-03-06 18:11:38 -08002135>>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')]
2136[True, True, True, False, False]
2137
Guido van Rossum805365e2007-05-07 22:24:25 +00002138>>> quantify(range(99), lambda x: x%2==0)
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000213950
2140
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00002141>>> a = [[1, 2, 3], [4, 5, 6]]
2142>>> flatten(a)
2143[1, 2, 3, 4, 5, 6]
2144
2145>>> list(repeatfunc(pow, 5, 2, 3))
2146[8, 8, 8, 8, 8]
2147
2148>>> import random
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002149>>> take(5, map(int, repeatfunc(random.random)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00002150[0, 0, 0, 0, 0]
2151
Raymond Hettingerd591f662003-10-26 15:34:50 +00002152>>> list(pairwise('abcd'))
2153[('a', 'b'), ('b', 'c'), ('c', 'd')]
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002154
Raymond Hettingerd591f662003-10-26 15:34:50 +00002155>>> list(pairwise([]))
2156[]
2157
2158>>> list(pairwise('a'))
Raymond Hettingerbefa37d2003-06-18 19:25:37 +00002159[]
2160
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002161>>> list(islice(padnone('abc'), 0, 6))
2162['a', 'b', 'c', None, None, None]
2163
2164>>> list(ncycles('abc', 3))
2165['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
2166
2167>>> dotproduct([1,2,3], [4,5,6])
216832
2169
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002170>>> list(grouper(3, 'abcdefg', 'x'))
2171[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x')]
2172
2173>>> list(roundrobin('abc', 'd', 'ef'))
2174['a', 'd', 'e', 'b', 'f', 'c']
2175
Raymond Hettingerace67332009-01-26 02:23:50 +00002176>>> list(powerset([1,2,3]))
2177[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002178
Raymond Hettinger191e8502009-01-27 13:29:43 +00002179>>> all(len(list(powerset(range(n)))) == 2**n for n in range(18))
2180True
2181
2182>>> list(powerset('abcde')) == sorted(sorted(set(powerset('abcde'))), key=len)
2183True
2184
Raymond Hettingerad9d96b2009-01-02 21:39:07 +00002185>>> list(unique_everseen('AAAABBBCCDAABBB'))
2186['A', 'B', 'C', 'D']
2187
2188>>> list(unique_everseen('ABBCcAD', str.lower))
2189['A', 'B', 'C', 'D']
2190
2191>>> list(unique_justseen('AAAABBBCCDAABBB'))
2192['A', 'B', 'C', 'D', 'A', 'B']
2193
2194>>> list(unique_justseen('ABBCcAD', str.lower))
2195['A', 'B', 'C', 'A', 'D']
2196
Raymond Hettinger31b26f62014-04-02 03:16:42 -07002197>>> first_true('ABC0DEF1', '9', str.isdigit)
2198'0'
2199
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002200"""
2201
2202__test__ = {'libreftest' : libreftest}
2203
2204def test_main(verbose=None):
Raymond Hettingera56f6b62003-08-29 23:09:58 +00002205 test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC,
Thomas Woutersb2137042007-02-01 18:02:27 +00002206 RegressionTests, LengthTransparency,
Serhiy Storchaka2dae92a2013-12-09 17:45:57 +02002207 SubclassWithKwargsTest, TestExamples,
2208 SizeofTest)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002209 support.run_unittest(*test_classes)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002210
2211 # verify reference counting
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002212 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger02420702003-06-29 20:36:23 +00002213 import gc
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00002214 counts = [None] * 5
Guido van Rossum805365e2007-05-07 22:24:25 +00002215 for i in range(len(counts)):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002216 support.run_unittest(*test_classes)
Raymond Hettinger02420702003-06-29 20:36:23 +00002217 gc.collect()
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00002218 counts[i] = sys.gettotalrefcount()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002219 print(counts)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002220
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002221 # doctest the examples in the library reference
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002222 support.run_doctest(sys.modules[__name__], verbose)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002223
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002224if __name__ == "__main__":
2225 test_main(verbose=True)