blob: 3aed77988e1260ef11b927a5c57407905aa8d1c7 [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
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000988 def test_repeat(self):
Raymond Hettingerf4bb7f22009-02-19 02:44:01 +0000989 self.assertEqual(list(repeat(object='a', times=3)), ['a', 'a', 'a'])
Guido van Rossum805365e2007-05-07 22:24:25 +0000990 self.assertEqual(lzip(range(3),repeat('a')),
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000991 [(0, 'a'), (1, 'a'), (2, 'a')])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000992 self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
Raymond Hettinger02420702003-06-29 20:36:23 +0000993 self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000994 self.assertEqual(list(repeat('a', 0)), [])
995 self.assertEqual(list(repeat('a', -3)), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000996 self.assertRaises(TypeError, repeat)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000997 self.assertRaises(TypeError, repeat, None, 3, 4)
998 self.assertRaises(TypeError, repeat, None, 'a')
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000999 r = repeat(1+0j)
1000 self.assertEqual(repr(r), 'repeat((1+0j))')
1001 r = repeat(1+0j, 5)
1002 self.assertEqual(repr(r), 'repeat((1+0j), 5)')
1003 list(r)
1004 self.assertEqual(repr(r), 'repeat((1+0j), 0)')
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001005
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001006 # check copy, deepcopy, pickle
1007 c = repeat(object='a', times=10)
1008 self.assertEqual(next(c), 'a')
1009 self.assertEqual(take(2, copy.copy(c)), list('a' * 2))
1010 self.assertEqual(take(2, copy.deepcopy(c)), list('a' * 2))
Serhiy Storchakabad12572014-12-15 14:03:42 +02001011 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1012 self.pickletest(proto, repeat(object='a', times=10))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001013
Raymond Hettinger97d35552014-06-24 21:36:58 -07001014 def test_repeat_with_negative_times(self):
1015 self.assertEqual(repr(repeat('a', -1)), "repeat('a', 0)")
1016 self.assertEqual(repr(repeat('a', -2)), "repeat('a', 0)")
1017 self.assertEqual(repr(repeat('a', times=-1)), "repeat('a', 0)")
1018 self.assertEqual(repr(repeat('a', times=-2)), "repeat('a', 0)")
1019
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001020 def test_map(self):
1021 self.assertEqual(list(map(operator.pow, range(3), range(1,7))),
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001022 [0**1, 1**2, 2**3])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001023 self.assertEqual(list(map(tupleize, 'abc', range(5))),
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001024 [('a',0),('b',1),('c',2)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001025 self.assertEqual(list(map(tupleize, 'abc', count())),
Raymond Hettinger02420702003-06-29 20:36:23 +00001026 [('a',0),('b',1),('c',2)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001027 self.assertEqual(take(2,map(tupleize, 'abc', count())),
Raymond Hettinger02420702003-06-29 20:36:23 +00001028 [('a',0),('b',1)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001029 self.assertEqual(list(map(operator.pow, [])), [])
1030 self.assertRaises(TypeError, map)
1031 self.assertRaises(TypeError, list, map(None, range(3), range(3)))
1032 self.assertRaises(TypeError, map, operator.neg)
1033 self.assertRaises(TypeError, next, map(10, range(5)))
1034 self.assertRaises(ValueError, next, map(errfunc, [4], [5]))
1035 self.assertRaises(TypeError, next, map(onearg, [4], [5]))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001036
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001037 # check copy, deepcopy, pickle
1038 ans = [('a',0),('b',1),('c',2)]
1039
1040 c = map(tupleize, 'abc', count())
1041 self.assertEqual(list(copy.copy(c)), ans)
1042
1043 c = map(tupleize, 'abc', count())
1044 self.assertEqual(list(copy.deepcopy(c)), ans)
1045
Serhiy Storchakabad12572014-12-15 14:03:42 +02001046 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1047 c = map(tupleize, 'abc', count())
1048 self.pickletest(proto, c)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001049
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001050 def test_starmap(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001051 self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
1052 [0**1, 1**2, 2**3])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001053 self.assertEqual(take(3, starmap(operator.pow, zip(count(), count(1)))),
Raymond Hettinger02420702003-06-29 20:36:23 +00001054 [0**1, 1**2, 2**3])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00001055 self.assertEqual(list(starmap(operator.pow, [])), [])
Christian Heimes679db4a2008-01-18 09:56:22 +00001056 self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5])
1057 self.assertRaises(TypeError, list, starmap(operator.pow, [None]))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00001058 self.assertRaises(TypeError, starmap)
1059 self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
Georg Brandla18af4e2007-04-21 15:47:16 +00001060 self.assertRaises(TypeError, next, starmap(10, [(4,5)]))
1061 self.assertRaises(ValueError, next, starmap(errfunc, [(4,5)]))
1062 self.assertRaises(TypeError, next, starmap(onearg, [(4,5)]))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001063
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001064 # check copy, deepcopy, pickle
1065 ans = [0**1, 1**2, 2**3]
1066
1067 c = starmap(operator.pow, zip(range(3), range(1,7)))
1068 self.assertEqual(list(copy.copy(c)), ans)
1069
1070 c = starmap(operator.pow, zip(range(3), range(1,7)))
1071 self.assertEqual(list(copy.deepcopy(c)), ans)
1072
Serhiy Storchakabad12572014-12-15 14:03:42 +02001073 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1074 c = starmap(operator.pow, zip(range(3), range(1,7)))
1075 self.pickletest(proto, c)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001076
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001077 def test_islice(self):
1078 for args in [ # islice(args) should agree with range(args)
1079 (10, 20, 3),
1080 (10, 3, 20),
1081 (10, 20),
1082 (10, 3),
1083 (20,)
1084 ]:
Guido van Rossum805365e2007-05-07 22:24:25 +00001085 self.assertEqual(list(islice(range(100), *args)),
1086 list(range(*args)))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001087
1088 for args, tgtargs in [ # Stop when seqn is exhausted
1089 ((10, 110, 3), ((10, 100, 3))),
1090 ((10, 110), ((10, 100))),
1091 ((110,), (100,))
1092 ]:
Guido van Rossum805365e2007-05-07 22:24:25 +00001093 self.assertEqual(list(islice(range(100), *args)),
1094 list(range(*tgtargs)))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001095
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001096 # Test stop=None
Guido van Rossum805365e2007-05-07 22:24:25 +00001097 self.assertEqual(list(islice(range(10), None)), list(range(10)))
1098 self.assertEqual(list(islice(range(10), None, None)), list(range(10)))
1099 self.assertEqual(list(islice(range(10), None, None, None)), list(range(10)))
1100 self.assertEqual(list(islice(range(10), 2, None)), list(range(2, 10)))
1101 self.assertEqual(list(islice(range(10), 1, None, 2)), list(range(1, 10, 2)))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001102
Raymond Hettingerfdf3bd62005-03-27 20:11:44 +00001103 # Test number of items consumed SF #1171417
1104 it = iter(range(10))
Guido van Rossum805365e2007-05-07 22:24:25 +00001105 self.assertEqual(list(islice(it, 3)), list(range(3)))
1106 self.assertEqual(list(it), list(range(3, 10)))
Raymond Hettingerfdf3bd62005-03-27 20:11:44 +00001107
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001108 # Test invalid arguments
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001109 ra = range(10)
1110 self.assertRaises(TypeError, islice, ra)
1111 self.assertRaises(TypeError, islice, ra, 1, 2, 3, 4)
1112 self.assertRaises(ValueError, islice, ra, -5, 10, 1)
1113 self.assertRaises(ValueError, islice, ra, 1, -5, -1)
1114 self.assertRaises(ValueError, islice, ra, 1, 10, -1)
1115 self.assertRaises(ValueError, islice, ra, 1, 10, 0)
1116 self.assertRaises(ValueError, islice, ra, 'a')
1117 self.assertRaises(ValueError, islice, ra, 'a', 1)
1118 self.assertRaises(ValueError, islice, ra, 1, 'a')
1119 self.assertRaises(ValueError, islice, ra, 'a', 1, 1)
1120 self.assertRaises(ValueError, islice, ra, 1, 'a', 1)
Guido van Rossum360e4b82007-05-14 22:51:27 +00001121 self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001122
Raymond Hettinger69b34bf2010-11-30 02:49:29 +00001123 # Issue #10323: Less islice in a predictable state
1124 c = count()
1125 self.assertEqual(list(islice(c, 1, 3, 50)), [1])
1126 self.assertEqual(next(c), 3)
1127
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001128 # check copy, deepcopy, pickle
1129 for args in [ # islice(args) should agree with range(args)
1130 (10, 20, 3),
1131 (10, 3, 20),
1132 (10, 20),
1133 (10, 3),
1134 (20,)
1135 ]:
1136 self.assertEqual(list(copy.copy(islice(range(100), *args))),
1137 list(range(*args)))
1138 self.assertEqual(list(copy.deepcopy(islice(range(100), *args))),
1139 list(range(*args)))
Serhiy Storchakabad12572014-12-15 14:03:42 +02001140 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1141 self.pickletest(proto, islice(range(100), *args))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001142
Antoine Pitrou26f82ef2014-04-29 12:13:46 +02001143 # Issue #21321: check source iterator is not referenced
1144 # from islice() after the latter has been exhausted
1145 it = (x for x in (1, 2))
1146 wr = weakref.ref(it)
1147 it = islice(it, 1)
1148 self.assertIsNotNone(wr())
1149 list(it) # exhaust the iterator
Benjamin Peterson8e163512014-08-24 18:07:28 -05001150 support.gc_collect()
Antoine Pitrou26f82ef2014-04-29 12:13:46 +02001151 self.assertIsNone(wr())
1152
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001153 def test_takewhile(self):
1154 data = [1, 3, 5, 20, 2, 4, 6, 8]
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001155 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00001156 self.assertEqual(list(takewhile(underten, [])), [])
1157 self.assertRaises(TypeError, takewhile)
1158 self.assertRaises(TypeError, takewhile, operator.pow)
1159 self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
Georg Brandla18af4e2007-04-21 15:47:16 +00001160 self.assertRaises(TypeError, next, takewhile(10, [(4,5)]))
1161 self.assertRaises(ValueError, next, takewhile(errfunc, [(4,5)]))
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001162 t = takewhile(bool, [1, 1, 1, 0, 0, 0])
1163 self.assertEqual(list(t), [1, 1, 1])
Georg Brandla18af4e2007-04-21 15:47:16 +00001164 self.assertRaises(StopIteration, next, t)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001165
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001166 # check copy, deepcopy, pickle
1167 self.assertEqual(list(copy.copy(takewhile(underten, data))), [1, 3, 5])
1168 self.assertEqual(list(copy.deepcopy(takewhile(underten, data))),
1169 [1, 3, 5])
Serhiy Storchakabad12572014-12-15 14:03:42 +02001170 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1171 self.pickletest(proto, takewhile(underten, data))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001172
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001173 def test_dropwhile(self):
1174 data = [1, 3, 5, 20, 2, 4, 6, 8]
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001175 self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00001176 self.assertEqual(list(dropwhile(underten, [])), [])
1177 self.assertRaises(TypeError, dropwhile)
1178 self.assertRaises(TypeError, dropwhile, operator.pow)
1179 self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
Georg Brandla18af4e2007-04-21 15:47:16 +00001180 self.assertRaises(TypeError, next, dropwhile(10, [(4,5)]))
1181 self.assertRaises(ValueError, next, dropwhile(errfunc, [(4,5)]))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001182
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001183 # check copy, deepcopy, pickle
1184 self.assertEqual(list(copy.copy(dropwhile(underten, data))), [20, 2, 4, 6, 8])
1185 self.assertEqual(list(copy.deepcopy(dropwhile(underten, data))),
1186 [20, 2, 4, 6, 8])
Serhiy Storchakabad12572014-12-15 14:03:42 +02001187 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1188 self.pickletest(proto, dropwhile(underten, data))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001189
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001190 def test_tee(self):
Raymond Hettingerad983e72003-11-12 14:32:26 +00001191 n = 200
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001192
1193 a, b = tee([]) # test empty iterator
1194 self.assertEqual(list(a), [])
1195 self.assertEqual(list(b), [])
1196
1197 a, b = tee(irange(n)) # test 100% interleaved
Guido van Rossum801f0d72006-08-24 19:48:10 +00001198 self.assertEqual(lzip(a,b), lzip(range(n), range(n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001199
1200 a, b = tee(irange(n)) # test 0% interleaved
Guido van Rossum805365e2007-05-07 22:24:25 +00001201 self.assertEqual(list(a), list(range(n)))
1202 self.assertEqual(list(b), list(range(n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001203
1204 a, b = tee(irange(n)) # test dealloc of leading iterator
Guido van Rossum805365e2007-05-07 22:24:25 +00001205 for i in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +00001206 self.assertEqual(next(a), i)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001207 del a
Guido van Rossum805365e2007-05-07 22:24:25 +00001208 self.assertEqual(list(b), list(range(n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001209
1210 a, b = tee(irange(n)) # test dealloc of trailing iterator
Guido van Rossum805365e2007-05-07 22:24:25 +00001211 for i in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +00001212 self.assertEqual(next(a), i)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001213 del b
Guido van Rossum805365e2007-05-07 22:24:25 +00001214 self.assertEqual(list(a), list(range(100, n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001215
Guido van Rossum805365e2007-05-07 22:24:25 +00001216 for j in range(5): # test randomly interleaved
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001217 order = [0]*n + [1]*n
1218 random.shuffle(order)
1219 lists = ([], [])
1220 its = tee(irange(n))
1221 for i in order:
Georg Brandla18af4e2007-04-21 15:47:16 +00001222 value = next(its[i])
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001223 lists[i].append(value)
Guido van Rossum805365e2007-05-07 22:24:25 +00001224 self.assertEqual(lists[0], list(range(n)))
1225 self.assertEqual(lists[1], list(range(n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001226
Raymond Hettingerad983e72003-11-12 14:32:26 +00001227 # test argument format checking
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001228 self.assertRaises(TypeError, tee)
1229 self.assertRaises(TypeError, tee, 3)
1230 self.assertRaises(TypeError, tee, [1,2], 'x')
Raymond Hettingerad983e72003-11-12 14:32:26 +00001231 self.assertRaises(TypeError, tee, [1,2], 3, 'x')
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001232
Raymond Hettingerad983e72003-11-12 14:32:26 +00001233 # tee object should be instantiable
1234 a, b = tee('abc')
1235 c = type(a)('def')
1236 self.assertEqual(list(c), list('def'))
Raymond Hettingerf0c5aec2003-10-26 14:25:56 +00001237
Raymond Hettingerad983e72003-11-12 14:32:26 +00001238 # test long-lagged and multi-way split
Guido van Rossum805365e2007-05-07 22:24:25 +00001239 a, b, c = tee(range(2000), 3)
1240 for i in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +00001241 self.assertEqual(next(a), i)
Guido van Rossum805365e2007-05-07 22:24:25 +00001242 self.assertEqual(list(b), list(range(2000)))
1243 self.assertEqual([next(c), next(c)], list(range(2)))
1244 self.assertEqual(list(a), list(range(100,2000)))
1245 self.assertEqual(list(c), list(range(2,2000)))
Raymond Hettingerad983e72003-11-12 14:32:26 +00001246
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001247 # test values of n
1248 self.assertRaises(TypeError, tee, 'abc', 'invalid')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001249 self.assertRaises(ValueError, tee, [], -1)
Guido van Rossum805365e2007-05-07 22:24:25 +00001250 for n in range(5):
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001251 result = tee('abc', n)
1252 self.assertEqual(type(result), tuple)
1253 self.assertEqual(len(result), n)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001254 self.assertEqual([list(x) for x in result], [list('abc')]*n)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001255
Raymond Hettingerad983e72003-11-12 14:32:26 +00001256 # tee pass-through to copyable iterator
1257 a, b = tee('abc')
1258 c, d = tee(a)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001259 self.assertTrue(a is c)
Raymond Hettingerad983e72003-11-12 14:32:26 +00001260
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001261 # test tee_new
1262 t1, t2 = tee('abc')
1263 tnew = type(t1)
1264 self.assertRaises(TypeError, tnew)
1265 self.assertRaises(TypeError, tnew, 10)
1266 t3 = tnew(t1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001267 self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc'))
Raymond Hettingerf0c5aec2003-10-26 14:25:56 +00001268
Raymond Hettingera9f60922004-10-17 16:40:14 +00001269 # test that tee objects are weak referencable
Guido van Rossum805365e2007-05-07 22:24:25 +00001270 a, b = tee(range(10))
Antoine Pitrou26f82ef2014-04-29 12:13:46 +02001271 p = weakref.proxy(a)
Raymond Hettingera9f60922004-10-17 16:40:14 +00001272 self.assertEqual(getattr(p, '__class__'), type(b))
1273 del a
1274 self.assertRaises(ReferenceError, getattr, p, '__class__')
1275
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001276 ans = list('abc')
1277 long_ans = list(range(10000))
1278
1279 # check copy
1280 a, b = tee('abc')
1281 self.assertEqual(list(copy.copy(a)), ans)
1282 self.assertEqual(list(copy.copy(b)), ans)
1283 a, b = tee(list(range(10000)))
1284 self.assertEqual(list(copy.copy(a)), long_ans)
1285 self.assertEqual(list(copy.copy(b)), long_ans)
1286
1287 # check partially consumed copy
1288 a, b = tee('abc')
1289 take(2, a)
1290 take(1, b)
1291 self.assertEqual(list(copy.copy(a)), ans[2:])
1292 self.assertEqual(list(copy.copy(b)), ans[1:])
1293 self.assertEqual(list(a), ans[2:])
1294 self.assertEqual(list(b), ans[1:])
1295 a, b = tee(range(10000))
1296 take(100, a)
1297 take(60, b)
1298 self.assertEqual(list(copy.copy(a)), long_ans[100:])
1299 self.assertEqual(list(copy.copy(b)), long_ans[60:])
1300 self.assertEqual(list(a), long_ans[100:])
1301 self.assertEqual(list(b), long_ans[60:])
1302
1303 # check deepcopy
1304 a, b = tee('abc')
1305 self.assertEqual(list(copy.deepcopy(a)), ans)
1306 self.assertEqual(list(copy.deepcopy(b)), ans)
1307 self.assertEqual(list(a), ans)
1308 self.assertEqual(list(b), ans)
1309 a, b = tee(range(10000))
1310 self.assertEqual(list(copy.deepcopy(a)), long_ans)
1311 self.assertEqual(list(copy.deepcopy(b)), long_ans)
1312 self.assertEqual(list(a), long_ans)
1313 self.assertEqual(list(b), long_ans)
1314
1315 # check partially consumed deepcopy
1316 a, b = tee('abc')
1317 take(2, a)
1318 take(1, b)
1319 self.assertEqual(list(copy.deepcopy(a)), ans[2:])
1320 self.assertEqual(list(copy.deepcopy(b)), ans[1:])
1321 self.assertEqual(list(a), ans[2:])
1322 self.assertEqual(list(b), ans[1:])
1323 a, b = tee(range(10000))
1324 take(100, a)
1325 take(60, b)
1326 self.assertEqual(list(copy.deepcopy(a)), long_ans[100:])
1327 self.assertEqual(list(copy.deepcopy(b)), long_ans[60:])
1328 self.assertEqual(list(a), long_ans[100:])
1329 self.assertEqual(list(b), long_ans[60:])
1330
1331 # check pickle
Serhiy Storchakabad12572014-12-15 14:03:42 +02001332 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1333 self.pickletest(proto, iter(tee('abc')))
1334 a, b = tee('abc')
1335 self.pickletest(proto, a, compare=ans)
1336 self.pickletest(proto, b, compare=ans)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001337
Serhiy Storchakaa3e91282013-01-25 13:19:31 +02001338 # Issue 13454: Crash when deleting backward iterator from tee()
1339 def test_tee_del_backward(self):
Serhiy Storchaka5bb893c2013-01-26 11:52:06 +02001340 forward, backward = tee(repeat(None, 20000000))
Serhiy Storchaka9db55002015-03-28 20:38:37 +02001341 try:
1342 any(forward) # exhaust the iterator
1343 del backward
1344 except:
1345 del forward, backward
1346 raise
Serhiy Storchakaa3e91282013-01-25 13:19:31 +02001347
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001348 def test_StopIteration(self):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001349 self.assertRaises(StopIteration, next, zip())
Raymond Hettingerb5a42082003-08-08 05:10:41 +00001350
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001351 for f in (chain, cycle, zip, groupby):
Georg Brandla18af4e2007-04-21 15:47:16 +00001352 self.assertRaises(StopIteration, next, f([]))
1353 self.assertRaises(StopIteration, next, f(StopNow()))
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001354
Georg Brandla18af4e2007-04-21 15:47:16 +00001355 self.assertRaises(StopIteration, next, islice([], None))
1356 self.assertRaises(StopIteration, next, islice(StopNow(), None))
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001357
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001358 p, q = tee([])
Georg Brandla18af4e2007-04-21 15:47:16 +00001359 self.assertRaises(StopIteration, next, p)
1360 self.assertRaises(StopIteration, next, q)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001361 p, q = tee(StopNow())
Georg Brandla18af4e2007-04-21 15:47:16 +00001362 self.assertRaises(StopIteration, next, p)
1363 self.assertRaises(StopIteration, next, q)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001364
Georg Brandla18af4e2007-04-21 15:47:16 +00001365 self.assertRaises(StopIteration, next, repeat(None, 0))
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001366
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001367 for f in (filter, filterfalse, map, takewhile, dropwhile, starmap):
Georg Brandla18af4e2007-04-21 15:47:16 +00001368 self.assertRaises(StopIteration, next, f(lambda x:x, []))
1369 self.assertRaises(StopIteration, next, f(lambda x:x, StopNow()))
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001370
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001371class TestExamples(unittest.TestCase):
1372
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001373 def test_accumulate(self):
Raymond Hettinger482ba772010-12-01 22:48:00 +00001374 self.assertEqual(list(accumulate([1,2,3,4,5])), [1, 3, 6, 10, 15])
1375
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001376 def test_accumulate_reducible(self):
1377 # check copy, deepcopy, pickle
1378 data = [1, 2, 3, 4, 5]
1379 accumulated = [1, 3, 6, 10, 15]
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001380
Serhiy Storchakabad12572014-12-15 14:03:42 +02001381 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1382 it = accumulate(data)
1383 self.assertEqual(list(pickle.loads(pickle.dumps(it, proto))), accumulated[:])
1384 self.assertEqual(next(it), 1)
1385 self.assertEqual(list(pickle.loads(pickle.dumps(it, proto))), accumulated[1:])
1386 it = accumulate(data)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001387 self.assertEqual(next(it), 1)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001388 self.assertEqual(list(copy.deepcopy(it)), accumulated[1:])
1389 self.assertEqual(list(copy.copy(it)), accumulated[1:])
1390
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001391 def test_chain(self):
1392 self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF')
1393
1394 def test_chain_from_iterable(self):
1395 self.assertEqual(''.join(chain.from_iterable(['ABC', 'DEF'])), 'ABCDEF')
1396
1397 def test_combinations(self):
1398 self.assertEqual(list(combinations('ABCD', 2)),
1399 [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
1400 self.assertEqual(list(combinations(range(4), 3)),
1401 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
1402
Raymond Hettingerd07d9392009-01-27 04:20:44 +00001403 def test_combinations_with_replacement(self):
1404 self.assertEqual(list(combinations_with_replacement('ABC', 2)),
1405 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
1406
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +00001407 def test_compress(self):
1408 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
1409
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001410 def test_count(self):
1411 self.assertEqual(list(islice(count(10), 5)), [10, 11, 12, 13, 14])
1412
1413 def test_cycle(self):
1414 self.assertEqual(list(islice(cycle('ABCD'), 12)), list('ABCDABCDABCD'))
1415
1416 def test_dropwhile(self):
1417 self.assertEqual(list(dropwhile(lambda x: x<5, [1,4,6,4,1])), [6,4,1])
1418
1419 def test_groupby(self):
1420 self.assertEqual([k for k, g in groupby('AAAABBBCCDAABBB')],
1421 list('ABCDAB'))
1422 self.assertEqual([(list(g)) for k, g in groupby('AAAABBBCCD')],
1423 [list('AAAA'), list('BBB'), list('CC'), list('D')])
1424
1425 def test_filter(self):
1426 self.assertEqual(list(filter(lambda x: x%2, range(10))), [1,3,5,7,9])
1427
1428 def test_filterfalse(self):
1429 self.assertEqual(list(filterfalse(lambda x: x%2, range(10))), [0,2,4,6,8])
1430
1431 def test_map(self):
1432 self.assertEqual(list(map(pow, (2,3,10), (5,2,3))), [32, 9, 1000])
1433
1434 def test_islice(self):
1435 self.assertEqual(list(islice('ABCDEFG', 2)), list('AB'))
1436 self.assertEqual(list(islice('ABCDEFG', 2, 4)), list('CD'))
1437 self.assertEqual(list(islice('ABCDEFG', 2, None)), list('CDEFG'))
1438 self.assertEqual(list(islice('ABCDEFG', 0, None, 2)), list('ACEG'))
1439
1440 def test_zip(self):
1441 self.assertEqual(list(zip('ABCD', 'xy')), [('A', 'x'), ('B', 'y')])
1442
1443 def test_zip_longest(self):
1444 self.assertEqual(list(zip_longest('ABCD', 'xy', fillvalue='-')),
1445 [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')])
1446
1447 def test_permutations(self):
1448 self.assertEqual(list(permutations('ABCD', 2)),
1449 list(map(tuple, 'AB AC AD BA BC BD CA CB CD DA DB DC'.split())))
1450 self.assertEqual(list(permutations(range(3))),
1451 [(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0)])
1452
1453 def test_product(self):
1454 self.assertEqual(list(product('ABCD', 'xy')),
1455 list(map(tuple, 'Ax Ay Bx By Cx Cy Dx Dy'.split())))
1456 self.assertEqual(list(product(range(2), repeat=3)),
1457 [(0,0,0), (0,0,1), (0,1,0), (0,1,1),
1458 (1,0,0), (1,0,1), (1,1,0), (1,1,1)])
1459
1460 def test_repeat(self):
1461 self.assertEqual(list(repeat(10, 3)), [10, 10, 10])
1462
1463 def test_stapmap(self):
1464 self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])),
1465 [32, 9, 1000])
1466
1467 def test_takewhile(self):
1468 self.assertEqual(list(takewhile(lambda x: x<5, [1,4,6,4,1])), [1,4])
1469
1470
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001471class TestGC(unittest.TestCase):
1472
1473 def makecycle(self, iterator, container):
1474 container.append(iterator)
Georg Brandla18af4e2007-04-21 15:47:16 +00001475 next(iterator)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001476 del container, iterator
1477
Raymond Hettinger482ba772010-12-01 22:48:00 +00001478 def test_accumulate(self):
1479 a = []
1480 self.makecycle(accumulate([1,2,a,3]), a)
1481
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001482 def test_chain(self):
1483 a = []
1484 self.makecycle(chain(a), a)
1485
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001486 def test_chain_from_iterable(self):
1487 a = []
1488 self.makecycle(chain.from_iterable([a]), a)
1489
1490 def test_combinations(self):
1491 a = []
1492 self.makecycle(combinations([1,2,a,3], 3), a)
1493
Raymond Hettingerd07d9392009-01-27 04:20:44 +00001494 def test_combinations_with_replacement(self):
1495 a = []
1496 self.makecycle(combinations_with_replacement([1,2,a,3], 3), a)
1497
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +00001498 def test_compress(self):
1499 a = []
1500 self.makecycle(compress('ABCDEF', [1,0,1,0,1,0]), a)
1501
Raymond Hettingerd6280f42009-02-16 20:50:56 +00001502 def test_count(self):
1503 a = []
1504 Int = type('Int', (int,), dict(x=a))
1505 self.makecycle(count(Int(0), Int(1)), a)
1506
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001507 def test_cycle(self):
1508 a = []
1509 self.makecycle(cycle([a]*2), a)
1510
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001511 def test_dropwhile(self):
1512 a = []
1513 self.makecycle(dropwhile(bool, [0, a, a]), a)
1514
1515 def test_groupby(self):
1516 a = []
1517 self.makecycle(groupby([a]*2, lambda x:x), a)
1518
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001519 def test_issue2246(self):
1520 # Issue 2246 -- the _grouper iterator was not included in GC
1521 n = 10
1522 keyfunc = lambda x: x
1523 for i, j in groupby(range(n), key=keyfunc):
1524 keyfunc.__dict__.setdefault('x',[]).append(j)
1525
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001526 def test_filter(self):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001527 a = []
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001528 self.makecycle(filter(lambda x:True, [a]*2), a)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001529
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001530 def test_filterfalse(self):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001531 a = []
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001532 self.makecycle(filterfalse(lambda x:False, a), a)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001533
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001534 def test_zip(self):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001535 a = []
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001536 self.makecycle(zip([a]*2, [a]*3), a)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001537
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001538 def test_zip_longest(self):
1539 a = []
1540 self.makecycle(zip_longest([a]*2, [a]*3), a)
1541 b = [a, None]
1542 self.makecycle(zip_longest([a]*2, [a]*3, fillvalue=b), a)
1543
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001544 def test_map(self):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001545 a = []
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001546 self.makecycle(map(lambda x:x, [a]*2), a)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001547
1548 def test_islice(self):
1549 a = []
1550 self.makecycle(islice([a]*2, None), a)
1551
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001552 def test_permutations(self):
1553 a = []
1554 self.makecycle(permutations([1,2,a,3], 3), a)
1555
1556 def test_product(self):
1557 a = []
1558 self.makecycle(product([1,2,a,3], repeat=3), a)
1559
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001560 def test_repeat(self):
1561 a = []
1562 self.makecycle(repeat(a), a)
1563
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001564 def test_starmap(self):
1565 a = []
1566 self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)
1567
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001568 def test_takewhile(self):
1569 a = []
1570 self.makecycle(takewhile(bool, [1, 0, a, a]), a)
1571
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001572def R(seqn):
1573 'Regular generator'
1574 for i in seqn:
1575 yield i
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001576
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001577class G:
1578 'Sequence using __getitem__'
1579 def __init__(self, seqn):
1580 self.seqn = seqn
1581 def __getitem__(self, i):
1582 return self.seqn[i]
1583
1584class I:
1585 'Sequence using iterator protocol'
1586 def __init__(self, seqn):
1587 self.seqn = seqn
1588 self.i = 0
1589 def __iter__(self):
1590 return self
Georg Brandla18af4e2007-04-21 15:47:16 +00001591 def __next__(self):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001592 if self.i >= len(self.seqn): raise StopIteration
1593 v = self.seqn[self.i]
1594 self.i += 1
1595 return v
1596
1597class Ig:
1598 'Sequence using iterator protocol defined with a generator'
1599 def __init__(self, seqn):
1600 self.seqn = seqn
1601 self.i = 0
1602 def __iter__(self):
1603 for val in self.seqn:
1604 yield val
1605
1606class X:
1607 'Missing __getitem__ and __iter__'
1608 def __init__(self, seqn):
1609 self.seqn = seqn
1610 self.i = 0
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 N:
Georg Brandla18af4e2007-04-21 15:47:16 +00001618 'Iterator missing __next__()'
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001619 def __init__(self, seqn):
1620 self.seqn = seqn
1621 self.i = 0
1622 def __iter__(self):
1623 return self
1624
1625class E:
1626 'Test propagation of exceptions'
1627 def __init__(self, seqn):
1628 self.seqn = seqn
1629 self.i = 0
1630 def __iter__(self):
1631 return self
Georg Brandla18af4e2007-04-21 15:47:16 +00001632 def __next__(self):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +00001633 3 // 0
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001634
1635class S:
1636 'Test immediate stop'
1637 def __init__(self, seqn):
1638 pass
1639 def __iter__(self):
1640 return self
Georg Brandla18af4e2007-04-21 15:47:16 +00001641 def __next__(self):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001642 raise StopIteration
1643
1644def L(seqn):
1645 'Test multiple tiers of iterators'
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001646 return chain(map(lambda x:x, R(Ig(G(seqn)))))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001647
1648
1649class TestVariousIteratorArgs(unittest.TestCase):
1650
Raymond Hettinger482ba772010-12-01 22:48:00 +00001651 def test_accumulate(self):
1652 s = [1,2,3,4,5]
1653 r = [1,3,6,10,15]
1654 n = len(s)
1655 for g in (G, I, Ig, L, R):
1656 self.assertEqual(list(accumulate(g(s))), r)
1657 self.assertEqual(list(accumulate(S(s))), [])
1658 self.assertRaises(TypeError, accumulate, X(s))
1659 self.assertRaises(TypeError, accumulate, N(s))
1660 self.assertRaises(ZeroDivisionError, list, accumulate(E(s)))
1661
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001662 def test_chain(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001663 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001664 for g in (G, I, Ig, S, L, R):
1665 self.assertEqual(list(chain(g(s))), list(g(s)))
1666 self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
Christian Heimesf16baeb2008-02-29 14:57:44 +00001667 self.assertRaises(TypeError, list, chain(X(s)))
Mark Dickinson26a96fa2008-03-01 02:27:46 +00001668 self.assertRaises(TypeError, list, chain(N(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001669 self.assertRaises(ZeroDivisionError, list, chain(E(s)))
1670
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +00001671 def test_compress(self):
1672 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
1673 n = len(s)
1674 for g in (G, I, Ig, S, L, R):
1675 self.assertEqual(list(compress(g(s), repeat(1))), list(g(s)))
1676 self.assertRaises(TypeError, compress, X(s), repeat(1))
1677 self.assertRaises(TypeError, compress, N(s), repeat(1))
1678 self.assertRaises(ZeroDivisionError, list, compress(E(s), repeat(1)))
1679
Christian Heimesc3f30c42008-02-22 16:37:40 +00001680 def test_product(self):
1681 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
1682 self.assertRaises(TypeError, product, X(s))
1683 self.assertRaises(TypeError, product, N(s))
1684 self.assertRaises(ZeroDivisionError, product, E(s))
1685
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001686 def test_cycle(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001687 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001688 for g in (G, I, Ig, S, L, R):
1689 tgtlen = len(s) * 3
1690 expected = list(g(s))*3
1691 actual = list(islice(cycle(g(s)), tgtlen))
1692 self.assertEqual(actual, expected)
1693 self.assertRaises(TypeError, cycle, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001694 self.assertRaises(TypeError, cycle, N(s))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001695 self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
1696
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001697 def test_groupby(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001698 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001699 for g in (G, I, Ig, S, L, R):
1700 self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
1701 self.assertRaises(TypeError, groupby, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001702 self.assertRaises(TypeError, groupby, N(s))
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001703 self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
1704
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001705 def test_filter(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001706 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001707 for g in (G, I, Ig, S, L, R):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001708 self.assertEqual(list(filter(isEven, g(s))),
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001709 [x for x in g(s) if isEven(x)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001710 self.assertRaises(TypeError, filter, isEven, X(s))
1711 self.assertRaises(TypeError, filter, isEven, N(s))
1712 self.assertRaises(ZeroDivisionError, list, filter(isEven, E(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001713
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001714 def test_filterfalse(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001715 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001716 for g in (G, I, Ig, S, L, R):
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001717 self.assertEqual(list(filterfalse(isEven, g(s))),
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001718 [x for x in g(s) if isOdd(x)])
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001719 self.assertRaises(TypeError, filterfalse, isEven, X(s))
1720 self.assertRaises(TypeError, filterfalse, isEven, N(s))
1721 self.assertRaises(ZeroDivisionError, list, filterfalse(isEven, E(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001722
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001723 def test_zip(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001724 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001725 for g in (G, I, Ig, S, L, R):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001726 self.assertEqual(list(zip(g(s))), lzip(g(s)))
1727 self.assertEqual(list(zip(g(s), g(s))), lzip(g(s), g(s)))
1728 self.assertRaises(TypeError, zip, X(s))
1729 self.assertRaises(TypeError, zip, N(s))
1730 self.assertRaises(ZeroDivisionError, list, zip(E(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001731
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001732 def test_ziplongest(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001733 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001734 for g in (G, I, Ig, S, L, R):
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001735 self.assertEqual(list(zip_longest(g(s))), list(zip(g(s))))
1736 self.assertEqual(list(zip_longest(g(s), g(s))), list(zip(g(s), g(s))))
1737 self.assertRaises(TypeError, zip_longest, X(s))
1738 self.assertRaises(TypeError, zip_longest, N(s))
1739 self.assertRaises(ZeroDivisionError, list, zip_longest(E(s)))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001740
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001741 def test_map(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001742 for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001743 for g in (G, I, Ig, S, L, R):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001744 self.assertEqual(list(map(onearg, g(s))),
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001745 [onearg(x) for x in g(s)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001746 self.assertEqual(list(map(operator.pow, g(s), g(s))),
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001747 [x**x for x in g(s)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001748 self.assertRaises(TypeError, map, onearg, X(s))
1749 self.assertRaises(TypeError, map, onearg, N(s))
1750 self.assertRaises(ZeroDivisionError, list, map(onearg, E(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001751
1752 def test_islice(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001753 for s in ("12345", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001754 for g in (G, I, Ig, S, L, R):
1755 self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
1756 self.assertRaises(TypeError, islice, X(s), 10)
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001757 self.assertRaises(TypeError, islice, N(s), 10)
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001758 self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
1759
1760 def test_starmap(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001761 for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001762 for g in (G, I, Ig, S, L, R):
Guido van Rossum801f0d72006-08-24 19:48:10 +00001763 ss = lzip(s, s)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001764 self.assertEqual(list(starmap(operator.pow, g(ss))),
1765 [x**x for x in g(s)])
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001766 self.assertRaises(TypeError, starmap, operator.pow, X(ss))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001767 self.assertRaises(TypeError, starmap, operator.pow, N(ss))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001768 self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
1769
1770 def test_takewhile(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001771 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001772 for g in (G, I, Ig, S, L, R):
1773 tgt = []
1774 for elem in g(s):
1775 if not isEven(elem): break
1776 tgt.append(elem)
1777 self.assertEqual(list(takewhile(isEven, g(s))), tgt)
1778 self.assertRaises(TypeError, takewhile, isEven, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001779 self.assertRaises(TypeError, takewhile, isEven, N(s))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001780 self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
1781
1782 def test_dropwhile(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001783 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001784 for g in (G, I, Ig, S, L, R):
1785 tgt = []
1786 for elem in g(s):
1787 if not tgt and isOdd(elem): continue
1788 tgt.append(elem)
1789 self.assertEqual(list(dropwhile(isOdd, g(s))), tgt)
1790 self.assertRaises(TypeError, dropwhile, isOdd, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001791 self.assertRaises(TypeError, dropwhile, isOdd, N(s))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001792 self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
1793
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001794 def test_tee(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001795 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001796 for g in (G, I, Ig, S, L, R):
1797 it1, it2 = tee(g(s))
1798 self.assertEqual(list(it1), list(g(s)))
1799 self.assertEqual(list(it2), list(g(s)))
1800 self.assertRaises(TypeError, tee, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001801 self.assertRaises(TypeError, tee, N(s))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001802 self.assertRaises(ZeroDivisionError, list, tee(E(s))[0])
1803
Raymond Hettinger5cab2e32004-02-10 09:25:40 +00001804class LengthTransparency(unittest.TestCase):
1805
1806 def test_repeat(self):
Armin Ronacheraa9a79d2012-10-06 14:03:24 +02001807 self.assertEqual(operator.length_hint(repeat(None, 50)), 50)
Raymond Hettinger97d35552014-06-24 21:36:58 -07001808 self.assertEqual(operator.length_hint(repeat(None, 0)), 0)
Armin Ronacheraa9a79d2012-10-06 14:03:24 +02001809 self.assertEqual(operator.length_hint(repeat(None), 12), 12)
Raymond Hettinger5cab2e32004-02-10 09:25:40 +00001810
Raymond Hettinger97d35552014-06-24 21:36:58 -07001811 def test_repeat_with_negative_times(self):
1812 self.assertEqual(operator.length_hint(repeat(None, -1)), 0)
1813 self.assertEqual(operator.length_hint(repeat(None, -2)), 0)
1814 self.assertEqual(operator.length_hint(repeat(None, times=-1)), 0)
1815 self.assertEqual(operator.length_hint(repeat(None, times=-2)), 0)
1816
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001817class RegressionTests(unittest.TestCase):
1818
1819 def test_sf_793826(self):
1820 # Fix Armin Rigo's successful efforts to wreak havoc
1821
1822 def mutatingtuple(tuple1, f, tuple2):
1823 # this builds a tuple t which is a copy of tuple1,
1824 # then calls f(t), then mutates t to be equal to tuple2
1825 # (needs len(tuple1) == len(tuple2)).
1826 def g(value, first=[1]):
1827 if first:
1828 del first[:]
Georg Brandla18af4e2007-04-21 15:47:16 +00001829 f(next(z))
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001830 return value
1831 items = list(tuple2)
1832 items[1:1] = list(tuple1)
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001833 gen = map(g, items)
1834 z = zip(*[gen]*len(tuple1))
Georg Brandla18af4e2007-04-21 15:47:16 +00001835 next(z)
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001836
1837 def f(t):
1838 global T
1839 T = t
1840 first[:] = list(T)
1841
1842 first = []
1843 mutatingtuple((1,2,3), f, (4,5,6))
1844 second = list(T)
1845 self.assertEqual(first, second)
1846
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001847
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001848 def test_sf_950057(self):
1849 # Make sure that chain() and cycle() catch exceptions immediately
1850 # rather than when shifting between input sources
1851
1852 def gen1():
1853 hist.append(0)
1854 yield 1
1855 hist.append(1)
Tim Petersbeb7c0c2004-07-18 17:34:03 +00001856 raise AssertionError
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001857 hist.append(2)
1858
1859 def gen2(x):
1860 hist.append(3)
1861 yield 2
1862 hist.append(4)
1863 if x:
1864 raise StopIteration
1865
1866 hist = []
1867 self.assertRaises(AssertionError, list, chain(gen1(), gen2(False)))
1868 self.assertEqual(hist, [0,1])
1869
1870 hist = []
1871 self.assertRaises(AssertionError, list, chain(gen1(), gen2(True)))
1872 self.assertEqual(hist, [0,1])
1873
1874 hist = []
1875 self.assertRaises(AssertionError, list, cycle(gen1()))
1876 self.assertEqual(hist, [0,1])
1877
Thomas Woutersb2137042007-02-01 18:02:27 +00001878class SubclassWithKwargsTest(unittest.TestCase):
1879 def test_keywords_in_subclass(self):
1880 # count is not subclassable...
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001881 for cls in (repeat, zip, filter, filterfalse, chain, map,
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +00001882 starmap, islice, takewhile, dropwhile, cycle, compress):
Thomas Woutersb2137042007-02-01 18:02:27 +00001883 class Subclass(cls):
1884 def __init__(self, newarg=None, *args):
1885 cls.__init__(self, *args)
1886 try:
1887 Subclass(newarg=1)
1888 except TypeError as err:
1889 # we expect type errors because of wrong argument count
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001890 self.assertNotIn("does not take keyword arguments", err.args[0])
Thomas Woutersb2137042007-02-01 18:02:27 +00001891
Serhiy Storchaka2dae92a2013-12-09 17:45:57 +02001892@support.cpython_only
1893class SizeofTest(unittest.TestCase):
1894 def setUp(self):
1895 self.ssize_t = struct.calcsize('n')
1896
1897 check_sizeof = support.check_sizeof
1898
1899 def test_product_sizeof(self):
1900 basesize = support.calcobjsize('3Pi')
1901 check = self.check_sizeof
1902 check(product('ab', '12'), basesize + 2 * self.ssize_t)
1903 check(product(*(('abc',) * 10)), basesize + 10 * self.ssize_t)
1904
1905 def test_combinations_sizeof(self):
1906 basesize = support.calcobjsize('3Pni')
1907 check = self.check_sizeof
1908 check(combinations('abcd', 3), basesize + 3 * self.ssize_t)
1909 check(combinations(range(10), 4), basesize + 4 * self.ssize_t)
1910
1911 def test_combinations_with_replacement_sizeof(self):
1912 cwr = combinations_with_replacement
1913 basesize = support.calcobjsize('3Pni')
1914 check = self.check_sizeof
1915 check(cwr('abcd', 3), basesize + 3 * self.ssize_t)
1916 check(cwr(range(10), 4), basesize + 4 * self.ssize_t)
1917
1918 def test_permutations_sizeof(self):
1919 basesize = support.calcobjsize('4Pni')
1920 check = self.check_sizeof
1921 check(permutations('abcd'),
1922 basesize + 4 * self.ssize_t + 4 * self.ssize_t)
1923 check(permutations('abcd', 3),
1924 basesize + 4 * self.ssize_t + 3 * self.ssize_t)
1925 check(permutations('abcde', 3),
1926 basesize + 5 * self.ssize_t + 3 * self.ssize_t)
1927 check(permutations(range(10), 4),
1928 basesize + 10 * self.ssize_t + 4 * self.ssize_t)
1929
Thomas Woutersb2137042007-02-01 18:02:27 +00001930
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001931libreftest = """ Doctest for examples in the library reference: libitertools.tex
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001932
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001933
1934>>> amounts = [120.15, 764.05, 823.14]
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001935>>> for checknum, amount in zip(count(1200), amounts):
Guido van Rossum7131f842007-02-09 20:13:25 +00001936... print('Check %d is for $%.2f' % (checknum, amount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001937...
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001938Check 1200 is for $120.15
1939Check 1201 is for $764.05
1940Check 1202 is for $823.14
1941
1942>>> import operator
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001943>>> for cube in map(operator.pow, range(1,4), repeat(3)):
Guido van Rossum7131f842007-02-09 20:13:25 +00001944... print(cube)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001945...
Raymond Hettinger96ef8112003-02-01 00:10:11 +000019461
19478
194827
1949
1950>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
Raymond Hettinger3567a872003-06-28 05:44:36 +00001951>>> for name in islice(reportlines, 3, None, 2):
Guido van Rossum7131f842007-02-09 20:13:25 +00001952... print(name.title())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001953...
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001954Alex
1955Laura
1956Martin
1957Walter
1958Samuele
1959
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001960>>> from operator import itemgetter
1961>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001962>>> di = sorted(sorted(d.items()), key=itemgetter(1))
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001963>>> for k, g in groupby(di, itemgetter(1)):
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001964... print(k, list(map(itemgetter(0), g)))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001965...
Raymond Hettingerd25c1c62003-12-06 16:23:06 +000019661 ['a', 'c', 'e']
19672 ['b', 'd', 'f']
19683 ['g']
1969
Raymond Hettinger734fb572004-01-20 20:04:40 +00001970# Find runs of consecutive numbers using groupby. The key to the solution
1971# is differencing with a range so that consecutive numbers all appear in
1972# same group.
1973>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001974>>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001975... print(list(map(operator.itemgetter(1), g)))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001976...
Raymond Hettinger734fb572004-01-20 20:04:40 +00001977[1]
1978[4, 5, 6]
1979[10]
1980[15, 16, 17, 18]
1981[22]
1982[25, 26, 27, 28]
1983
Georg Brandl3dbca812008-07-23 16:10:53 +00001984>>> def take(n, iterable):
1985... "Return first n items of the iterable as a list"
1986... return list(islice(iterable, n))
Raymond Hettingera098b332003-09-08 23:58:40 +00001987
Georg Brandl3dbca812008-07-23 16:10:53 +00001988>>> def enumerate(iterable, start=0):
1989... return zip(count(start), iterable)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001990
Georg Brandl3dbca812008-07-23 16:10:53 +00001991>>> def tabulate(function, start=0):
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001992... "Return function(0), function(1), ..."
Georg Brandl3dbca812008-07-23 16:10:53 +00001993... return map(function, count(start))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001994
Raymond Hettingercdf8ba32009-02-19 04:45:07 +00001995>>> def nth(iterable, n, default=None):
1996... "Returns the nth item or a default value"
1997... return next(islice(iterable, n, None), default)
Raymond Hettinger60eca932003-02-09 06:40:58 +00001998
Georg Brandl3dbca812008-07-23 16:10:53 +00001999>>> def quantify(iterable, pred=bool):
2000... "Count how many times the predicate is true"
2001... return sum(map(pred, iterable))
Raymond Hettinger60eca932003-02-09 06:40:58 +00002002
Georg Brandl3dbca812008-07-23 16:10:53 +00002003>>> def padnone(iterable):
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002004... "Returns the sequence elements and then returns None indefinitely"
Georg Brandl3dbca812008-07-23 16:10:53 +00002005... return chain(iterable, repeat(None))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002006
Georg Brandl3dbca812008-07-23 16:10:53 +00002007>>> def ncycles(iterable, n):
Ezio Melotti13925002011-03-16 11:05:33 +02002008... "Returns the sequence elements n times"
Georg Brandl3dbca812008-07-23 16:10:53 +00002009... return chain(*repeat(iterable, n))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002010
2011>>> def dotproduct(vec1, vec2):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002012... return sum(map(operator.mul, vec1, vec2))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002013
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00002014>>> def flatten(listOfLists):
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002015... return list(chain.from_iterable(listOfLists))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00002016
2017>>> def repeatfunc(func, times=None, *args):
2018... "Repeat calls to func with specified arguments."
2019... " Example: repeatfunc(random.random)"
2020... if times is None:
2021... return starmap(func, repeat(args))
2022... else:
2023... return starmap(func, repeat(args, times))
2024
Raymond Hettingerd591f662003-10-26 15:34:50 +00002025>>> def pairwise(iterable):
2026... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
2027... a, b = tee(iterable)
Raymond Hettingerad983e72003-11-12 14:32:26 +00002028... try:
Georg Brandla18af4e2007-04-21 15:47:16 +00002029... next(b)
Raymond Hettingerad983e72003-11-12 14:32:26 +00002030... except StopIteration:
2031... pass
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002032... return zip(a, b)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002033
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002034>>> def grouper(n, iterable, fillvalue=None):
Raymond Hettingerf5a2e472008-07-30 07:37:37 +00002035... "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002036... args = [iter(iterable)] * n
Raymond Hettinger883d2762009-01-27 04:57:51 +00002037... return zip_longest(*args, fillvalue=fillvalue)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002038
2039>>> def roundrobin(*iterables):
Raymond Hettingerf5a2e472008-07-30 07:37:37 +00002040... "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002041... # Recipe credited to George Sakkis
2042... pending = len(iterables)
2043... nexts = cycle(iter(it).__next__ for it in iterables)
2044... while pending:
2045... try:
2046... for next in nexts:
2047... yield next()
2048... except StopIteration:
2049... pending -= 1
2050... nexts = cycle(islice(nexts, pending))
2051
2052>>> def powerset(iterable):
Raymond Hettingerace67332009-01-26 02:23:50 +00002053... "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
2054... s = list(iterable)
2055... return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002056
Raymond Hettingerad9d96b2009-01-02 21:39:07 +00002057>>> def unique_everseen(iterable, key=None):
2058... "List unique elements, preserving order. Remember all elements ever seen."
2059... # unique_everseen('AAAABBBCCDAABBB') --> A B C D
2060... # unique_everseen('ABBCcAD', str.lower) --> A B C D
2061... seen = set()
2062... seen_add = seen.add
2063... if key is None:
2064... for element in iterable:
2065... if element not in seen:
2066... seen_add(element)
2067... yield element
2068... else:
2069... for element in iterable:
2070... k = key(element)
2071... if k not in seen:
2072... seen_add(k)
2073... yield element
2074
2075>>> def unique_justseen(iterable, key=None):
2076... "List unique elements, preserving order. Remember only the element just seen."
2077... # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
2078... # unique_justseen('ABBCcAD', str.lower) --> A B C A D
2079... return map(next, map(itemgetter(1), groupby(iterable, key)))
2080
Raymond Hettinger31b26f62014-04-02 03:16:42 -07002081>>> def first_true(iterable, default=False, pred=None):
2082... '''Returns the first true value in the iterable.
2083...
2084... If no true value is found, returns *default*
2085...
2086... If *pred* is not None, returns the first item
2087... for which pred(item) is true.
2088...
2089... '''
2090... # first_true([a,b,c], x) --> a or b or c or x
2091... # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
2092... return next(filter(pred, iterable), default)
2093
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002094This is not part of the examples but it tests to make sure the definitions
2095perform as purported.
2096
Raymond Hettingera098b332003-09-08 23:58:40 +00002097>>> take(10, count())
2098[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2099
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002100>>> list(enumerate('abc'))
2101[(0, 'a'), (1, 'b'), (2, 'c')]
2102
2103>>> list(islice(tabulate(lambda x: 2*x), 4))
2104[0, 2, 4, 6]
2105
2106>>> nth('abcde', 3)
Raymond Hettingerd04fa312009-02-04 19:45:13 +00002107'd'
2108
2109>>> nth('abcde', 9) is None
2110True
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002111
Guido van Rossum805365e2007-05-07 22:24:25 +00002112>>> quantify(range(99), lambda x: x%2==0)
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000211350
2114
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00002115>>> a = [[1, 2, 3], [4, 5, 6]]
2116>>> flatten(a)
2117[1, 2, 3, 4, 5, 6]
2118
2119>>> list(repeatfunc(pow, 5, 2, 3))
2120[8, 8, 8, 8, 8]
2121
2122>>> import random
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002123>>> take(5, map(int, repeatfunc(random.random)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00002124[0, 0, 0, 0, 0]
2125
Raymond Hettingerd591f662003-10-26 15:34:50 +00002126>>> list(pairwise('abcd'))
2127[('a', 'b'), ('b', 'c'), ('c', 'd')]
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002128
Raymond Hettingerd591f662003-10-26 15:34:50 +00002129>>> list(pairwise([]))
2130[]
2131
2132>>> list(pairwise('a'))
Raymond Hettingerbefa37d2003-06-18 19:25:37 +00002133[]
2134
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002135>>> list(islice(padnone('abc'), 0, 6))
2136['a', 'b', 'c', None, None, None]
2137
2138>>> list(ncycles('abc', 3))
2139['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
2140
2141>>> dotproduct([1,2,3], [4,5,6])
214232
2143
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002144>>> list(grouper(3, 'abcdefg', 'x'))
2145[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x')]
2146
2147>>> list(roundrobin('abc', 'd', 'ef'))
2148['a', 'd', 'e', 'b', 'f', 'c']
2149
Raymond Hettingerace67332009-01-26 02:23:50 +00002150>>> list(powerset([1,2,3]))
2151[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002152
Raymond Hettinger191e8502009-01-27 13:29:43 +00002153>>> all(len(list(powerset(range(n)))) == 2**n for n in range(18))
2154True
2155
2156>>> list(powerset('abcde')) == sorted(sorted(set(powerset('abcde'))), key=len)
2157True
2158
Raymond Hettingerad9d96b2009-01-02 21:39:07 +00002159>>> list(unique_everseen('AAAABBBCCDAABBB'))
2160['A', 'B', 'C', 'D']
2161
2162>>> list(unique_everseen('ABBCcAD', str.lower))
2163['A', 'B', 'C', 'D']
2164
2165>>> list(unique_justseen('AAAABBBCCDAABBB'))
2166['A', 'B', 'C', 'D', 'A', 'B']
2167
2168>>> list(unique_justseen('ABBCcAD', str.lower))
2169['A', 'B', 'C', 'A', 'D']
2170
Raymond Hettinger31b26f62014-04-02 03:16:42 -07002171>>> first_true('ABC0DEF1', '9', str.isdigit)
2172'0'
2173
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002174"""
2175
2176__test__ = {'libreftest' : libreftest}
2177
2178def test_main(verbose=None):
Raymond Hettingera56f6b62003-08-29 23:09:58 +00002179 test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC,
Thomas Woutersb2137042007-02-01 18:02:27 +00002180 RegressionTests, LengthTransparency,
Serhiy Storchaka2dae92a2013-12-09 17:45:57 +02002181 SubclassWithKwargsTest, TestExamples,
2182 SizeofTest)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002183 support.run_unittest(*test_classes)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002184
2185 # verify reference counting
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002186 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger02420702003-06-29 20:36:23 +00002187 import gc
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00002188 counts = [None] * 5
Guido van Rossum805365e2007-05-07 22:24:25 +00002189 for i in range(len(counts)):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002190 support.run_unittest(*test_classes)
Raymond Hettinger02420702003-06-29 20:36:23 +00002191 gc.collect()
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00002192 counts[i] = sys.gettotalrefcount()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002193 print(counts)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002194
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002195 # doctest the examples in the library reference
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002196 support.run_doctest(sys.modules[__name__], verbose)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002197
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002198if __name__ == "__main__":
2199 test_main(verbose=True)