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