PageRenderTime 60ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/test/test_itertools.py

http://unladen-swallow.googlecode.com/
Python | 1429 lines | 1397 code | 25 blank | 7 comment | 11 complexity | 4c68d56df57467d9f997ab83722d7b6f MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. import unittest
  2. from test import test_support
  3. from itertools import *
  4. from weakref import proxy
  5. import sys
  6. import operator
  7. import random
  8. maxsize = test_support.MAX_Py_ssize_t
  9. minsize = -maxsize-1
  10. def onearg(x):
  11. 'Test function of one argument'
  12. return 2*x
  13. def errfunc(*args):
  14. 'Test function that raises an error'
  15. raise ValueError
  16. def gen3():
  17. 'Non-restartable source sequence'
  18. for i in (0, 1, 2):
  19. yield i
  20. def isEven(x):
  21. 'Test predicate'
  22. return x%2==0
  23. def isOdd(x):
  24. 'Test predicate'
  25. return x%2==1
  26. class StopNow:
  27. 'Class emulating an empty iterable.'
  28. def __iter__(self):
  29. return self
  30. def next(self):
  31. raise StopIteration
  32. def take(n, seq):
  33. 'Convenience function for partially consuming a long of infinite iterable'
  34. return list(islice(seq, n))
  35. def prod(iterable):
  36. return reduce(operator.mul, iterable, 1)
  37. def fact(n):
  38. 'Factorial'
  39. return prod(range(1, n+1))
  40. class TestBasicOps(unittest.TestCase):
  41. def test_chain(self):
  42. def chain2(*iterables):
  43. 'Pure python version in the docs'
  44. for it in iterables:
  45. for element in it:
  46. yield element
  47. for c in (chain, chain2):
  48. self.assertEqual(list(c('abc', 'def')), list('abcdef'))
  49. self.assertEqual(list(c('abc')), list('abc'))
  50. self.assertEqual(list(c('')), [])
  51. self.assertEqual(take(4, c('abc', 'def')), list('abcd'))
  52. self.assertRaises(TypeError, list,c(2, 3))
  53. def test_chain_from_iterable(self):
  54. self.assertEqual(list(chain.from_iterable(['abc', 'def'])), list('abcdef'))
  55. self.assertEqual(list(chain.from_iterable(['abc'])), list('abc'))
  56. self.assertEqual(list(chain.from_iterable([''])), [])
  57. self.assertEqual(take(4, chain.from_iterable(['abc', 'def'])), list('abcd'))
  58. self.assertRaises(TypeError, list, chain.from_iterable([2, 3]))
  59. def test_combinations(self):
  60. self.assertRaises(TypeError, combinations, 'abc') # missing r argument
  61. self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments
  62. self.assertRaises(TypeError, combinations, None) # pool is not iterable
  63. self.assertRaises(ValueError, combinations, 'abc', -2) # r is negative
  64. self.assertEqual(list(combinations('abc', 32)), []) # r > n
  65. self.assertEqual(list(combinations(range(4), 3)),
  66. [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
  67. def combinations1(iterable, r):
  68. 'Pure python version shown in the docs'
  69. pool = tuple(iterable)
  70. n = len(pool)
  71. if r > n:
  72. return
  73. indices = range(r)
  74. yield tuple(pool[i] for i in indices)
  75. while 1:
  76. for i in reversed(range(r)):
  77. if indices[i] != i + n - r:
  78. break
  79. else:
  80. return
  81. indices[i] += 1
  82. for j in range(i+1, r):
  83. indices[j] = indices[j-1] + 1
  84. yield tuple(pool[i] for i in indices)
  85. def combinations2(iterable, r):
  86. 'Pure python version shown in the docs'
  87. pool = tuple(iterable)
  88. n = len(pool)
  89. for indices in permutations(range(n), r):
  90. if sorted(indices) == list(indices):
  91. yield tuple(pool[i] for i in indices)
  92. for n in range(7):
  93. values = [5*x-12 for x in range(n)]
  94. for r in range(n+2):
  95. result = list(combinations(values, r))
  96. self.assertEqual(len(result), 0 if r>n else fact(n) / fact(r) / fact(n-r)) # right number of combs
  97. self.assertEqual(len(result), len(set(result))) # no repeats
  98. self.assertEqual(result, sorted(result)) # lexicographic order
  99. for c in result:
  100. self.assertEqual(len(c), r) # r-length combinations
  101. self.assertEqual(len(set(c)), r) # no duplicate elements
  102. self.assertEqual(list(c), sorted(c)) # keep original ordering
  103. self.assert_(all(e in values for e in c)) # elements taken from input iterable
  104. self.assertEqual(list(c),
  105. [e for e in values if e in c]) # comb is a subsequence of the input iterable
  106. self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version
  107. self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version
  108. # Test implementation detail: tuple re-use
  109. self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1)
  110. self.assertNotEqual(len(set(map(id, list(combinations('abcde', 3))))), 1)
  111. def test_permutations(self):
  112. self.assertRaises(TypeError, permutations) # too few arguments
  113. self.assertRaises(TypeError, permutations, 'abc', 2, 1) # too many arguments
  114. self.assertRaises(TypeError, permutations, None) # pool is not iterable
  115. self.assertRaises(ValueError, permutations, 'abc', -2) # r is negative
  116. self.assertEqual(list(permutations('abc', 32)), []) # r > n
  117. self.assertRaises(TypeError, permutations, 'abc', 's') # r is not an int or None
  118. self.assertEqual(list(permutations(range(3), 2)),
  119. [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)])
  120. def permutations1(iterable, r=None):
  121. 'Pure python version shown in the docs'
  122. pool = tuple(iterable)
  123. n = len(pool)
  124. r = n if r is None else r
  125. if r > n:
  126. return
  127. indices = range(n)
  128. cycles = range(n, n-r, -1)
  129. yield tuple(pool[i] for i in indices[:r])
  130. while n:
  131. for i in reversed(range(r)):
  132. cycles[i] -= 1
  133. if cycles[i] == 0:
  134. indices[i:] = indices[i+1:] + indices[i:i+1]
  135. cycles[i] = n - i
  136. else:
  137. j = cycles[i]
  138. indices[i], indices[-j] = indices[-j], indices[i]
  139. yield tuple(pool[i] for i in indices[:r])
  140. break
  141. else:
  142. return
  143. def permutations2(iterable, r=None):
  144. 'Pure python version shown in the docs'
  145. pool = tuple(iterable)
  146. n = len(pool)
  147. r = n if r is None else r
  148. for indices in product(range(n), repeat=r):
  149. if len(set(indices)) == r:
  150. yield tuple(pool[i] for i in indices)
  151. for n in range(7):
  152. values = [5*x-12 for x in range(n)]
  153. for r in range(n+2):
  154. result = list(permutations(values, r))
  155. self.assertEqual(len(result), 0 if r>n else fact(n) / fact(n-r)) # right number of perms
  156. self.assertEqual(len(result), len(set(result))) # no repeats
  157. self.assertEqual(result, sorted(result)) # lexicographic order
  158. for p in result:
  159. self.assertEqual(len(p), r) # r-length permutations
  160. self.assertEqual(len(set(p)), r) # no duplicate elements
  161. self.assert_(all(e in values for e in p)) # elements taken from input iterable
  162. self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version
  163. self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version
  164. if r == n:
  165. self.assertEqual(result, list(permutations(values, None))) # test r as None
  166. self.assertEqual(result, list(permutations(values))) # test default r
  167. # Test implementation detail: tuple re-use
  168. self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1)
  169. self.assertNotEqual(len(set(map(id, list(permutations('abcde', 3))))), 1)
  170. def test_count(self):
  171. self.assertEqual(zip('abc',count()), [('a', 0), ('b', 1), ('c', 2)])
  172. self.assertEqual(zip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)])
  173. self.assertEqual(take(2, zip('abc',count(3))), [('a', 3), ('b', 4)])
  174. self.assertEqual(take(2, zip('abc',count(-1))), [('a', -1), ('b', 0)])
  175. self.assertEqual(take(2, zip('abc',count(-3))), [('a', -3), ('b', -2)])
  176. self.assertRaises(TypeError, count, 2, 3)
  177. self.assertRaises(TypeError, count, 'a')
  178. self.assertEqual(list(islice(count(maxsize-5), 10)), range(maxsize-5, maxsize+5))
  179. self.assertEqual(list(islice(count(-maxsize-5), 10)), range(-maxsize-5, -maxsize+5))
  180. c = count(3)
  181. self.assertEqual(repr(c), 'count(3)')
  182. c.next()
  183. self.assertEqual(repr(c), 'count(4)')
  184. c = count(-9)
  185. self.assertEqual(repr(c), 'count(-9)')
  186. c.next()
  187. self.assertEqual(c.next(), -8)
  188. for i in (-sys.maxint-5, -sys.maxint+5 ,-10, -1, 0, 10, sys.maxint-5, sys.maxint+5):
  189. # Test repr (ignoring the L in longs)
  190. r1 = repr(count(i)).replace('L', '')
  191. r2 = 'count(%r)'.__mod__(i).replace('L', '')
  192. self.assertEqual(r1, r2)
  193. def test_cycle(self):
  194. self.assertEqual(take(10, cycle('abc')), list('abcabcabca'))
  195. self.assertEqual(list(cycle('')), [])
  196. self.assertRaises(TypeError, cycle)
  197. self.assertRaises(TypeError, cycle, 5)
  198. self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0])
  199. def test_groupby(self):
  200. # Check whether it accepts arguments correctly
  201. self.assertEqual([], list(groupby([])))
  202. self.assertEqual([], list(groupby([], key=id)))
  203. self.assertRaises(TypeError, list, groupby('abc', []))
  204. self.assertRaises(TypeError, groupby, None)
  205. self.assertRaises(TypeError, groupby, 'abc', lambda x:x, 10)
  206. # Check normal input
  207. s = [(0, 10, 20), (0, 11,21), (0,12,21), (1,13,21), (1,14,22),
  208. (2,15,22), (3,16,23), (3,17,23)]
  209. dup = []
  210. for k, g in groupby(s, lambda r:r[0]):
  211. for elem in g:
  212. self.assertEqual(k, elem[0])
  213. dup.append(elem)
  214. self.assertEqual(s, dup)
  215. # Check nested case
  216. dup = []
  217. for k, g in groupby(s, lambda r:r[0]):
  218. for ik, ig in groupby(g, lambda r:r[2]):
  219. for elem in ig:
  220. self.assertEqual(k, elem[0])
  221. self.assertEqual(ik, elem[2])
  222. dup.append(elem)
  223. self.assertEqual(s, dup)
  224. # Check case where inner iterator is not used
  225. keys = [k for k, g in groupby(s, lambda r:r[0])]
  226. expectedkeys = set([r[0] for r in s])
  227. self.assertEqual(set(keys), expectedkeys)
  228. self.assertEqual(len(keys), len(expectedkeys))
  229. # Exercise pipes and filters style
  230. s = 'abracadabra'
  231. # sort s | uniq
  232. r = [k for k, g in groupby(sorted(s))]
  233. self.assertEqual(r, ['a', 'b', 'c', 'd', 'r'])
  234. # sort s | uniq -d
  235. r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))]
  236. self.assertEqual(r, ['a', 'b', 'r'])
  237. # sort s | uniq -c
  238. r = [(len(list(g)), k) for k, g in groupby(sorted(s))]
  239. self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')])
  240. # sort s | uniq -c | sort -rn | head -3
  241. r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3]
  242. self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')])
  243. # iter.next failure
  244. class ExpectedError(Exception):
  245. pass
  246. def delayed_raise(n=0):
  247. for i in range(n):
  248. yield 'yo'
  249. raise ExpectedError
  250. def gulp(iterable, keyp=None, func=list):
  251. return [func(g) for k, g in groupby(iterable, keyp)]
  252. # iter.next failure on outer object
  253. self.assertRaises(ExpectedError, gulp, delayed_raise(0))
  254. # iter.next failure on inner object
  255. self.assertRaises(ExpectedError, gulp, delayed_raise(1))
  256. # __cmp__ failure
  257. class DummyCmp:
  258. def __cmp__(self, dst):
  259. raise ExpectedError
  260. s = [DummyCmp(), DummyCmp(), None]
  261. # __cmp__ failure on outer object
  262. self.assertRaises(ExpectedError, gulp, s, func=id)
  263. # __cmp__ failure on inner object
  264. self.assertRaises(ExpectedError, gulp, s)
  265. # keyfunc failure
  266. def keyfunc(obj):
  267. if keyfunc.skip > 0:
  268. keyfunc.skip -= 1
  269. return obj
  270. else:
  271. raise ExpectedError
  272. # keyfunc failure on outer object
  273. keyfunc.skip = 0
  274. self.assertRaises(ExpectedError, gulp, [None], keyfunc)
  275. keyfunc.skip = 1
  276. self.assertRaises(ExpectedError, gulp, [None, None], keyfunc)
  277. def test_ifilter(self):
  278. self.assertEqual(list(ifilter(isEven, range(6))), [0,2,4])
  279. self.assertEqual(list(ifilter(None, [0,1,0,2,0])), [1,2])
  280. self.assertEqual(list(ifilter(bool, [0,1,0,2,0])), [1,2])
  281. self.assertEqual(take(4, ifilter(isEven, count())), [0,2,4,6])
  282. self.assertRaises(TypeError, ifilter)
  283. self.assertRaises(TypeError, ifilter, lambda x:x)
  284. self.assertRaises(TypeError, ifilter, lambda x:x, range(6), 7)
  285. self.assertRaises(TypeError, ifilter, isEven, 3)
  286. self.assertRaises(TypeError, ifilter(range(6), range(6)).next)
  287. def test_ifilterfalse(self):
  288. self.assertEqual(list(ifilterfalse(isEven, range(6))), [1,3,5])
  289. self.assertEqual(list(ifilterfalse(None, [0,1,0,2,0])), [0,0,0])
  290. self.assertEqual(list(ifilterfalse(bool, [0,1,0,2,0])), [0,0,0])
  291. self.assertEqual(take(4, ifilterfalse(isEven, count())), [1,3,5,7])
  292. self.assertRaises(TypeError, ifilterfalse)
  293. self.assertRaises(TypeError, ifilterfalse, lambda x:x)
  294. self.assertRaises(TypeError, ifilterfalse, lambda x:x, range(6), 7)
  295. self.assertRaises(TypeError, ifilterfalse, isEven, 3)
  296. self.assertRaises(TypeError, ifilterfalse(range(6), range(6)).next)
  297. def test_izip(self):
  298. ans = [(x,y) for x, y in izip('abc',count())]
  299. self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
  300. self.assertEqual(list(izip('abc', range(6))), zip('abc', range(6)))
  301. self.assertEqual(list(izip('abcdef', range(3))), zip('abcdef', range(3)))
  302. self.assertEqual(take(3,izip('abcdef', count())), zip('abcdef', range(3)))
  303. self.assertEqual(list(izip('abcdef')), zip('abcdef'))
  304. self.assertEqual(list(izip()), zip())
  305. self.assertRaises(TypeError, izip, 3)
  306. self.assertRaises(TypeError, izip, range(3), 3)
  307. # Check tuple re-use (implementation detail)
  308. self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')],
  309. zip('abc', 'def'))
  310. self.assertEqual([pair for pair in izip('abc', 'def')],
  311. zip('abc', 'def'))
  312. ids = map(id, izip('abc', 'def'))
  313. self.assertEqual(min(ids), max(ids))
  314. ids = map(id, list(izip('abc', 'def')))
  315. self.assertEqual(len(dict.fromkeys(ids)), len(ids))
  316. def test_iziplongest(self):
  317. for args in [
  318. ['abc', range(6)],
  319. [range(6), 'abc'],
  320. [range(1000), range(2000,2100), range(3000,3050)],
  321. [range(1000), range(0), range(3000,3050), range(1200), range(1500)],
  322. [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
  323. ]:
  324. target = map(None, *args)
  325. self.assertEqual(list(izip_longest(*args)), target)
  326. self.assertEqual(list(izip_longest(*args, **{})), target)
  327. target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X'
  328. self.assertEqual(list(izip_longest(*args, **dict(fillvalue='X'))), target)
  329. self.assertEqual(take(3,izip_longest('abcdef', count())), zip('abcdef', range(3))) # take 3 from infinite input
  330. self.assertEqual(list(izip_longest()), zip())
  331. self.assertEqual(list(izip_longest([])), zip([]))
  332. self.assertEqual(list(izip_longest('abcdef')), zip('abcdef'))
  333. self.assertEqual(list(izip_longest('abc', 'defg', **{})), map(None, 'abc', 'defg')) # empty keyword dict
  334. self.assertRaises(TypeError, izip_longest, 3)
  335. self.assertRaises(TypeError, izip_longest, range(3), 3)
  336. for stmt in [
  337. "izip_longest('abc', fv=1)",
  338. "izip_longest('abc', fillvalue=1, bogus_keyword=None)",
  339. ]:
  340. try:
  341. eval(stmt, globals(), locals())
  342. except TypeError:
  343. pass
  344. else:
  345. self.fail('Did not raise Type in: ' + stmt)
  346. # Check tuple re-use (implementation detail)
  347. self.assertEqual([tuple(list(pair)) for pair in izip_longest('abc', 'def')],
  348. zip('abc', 'def'))
  349. self.assertEqual([pair for pair in izip_longest('abc', 'def')],
  350. zip('abc', 'def'))
  351. ids = map(id, izip_longest('abc', 'def'))
  352. self.assertEqual(min(ids), max(ids))
  353. ids = map(id, list(izip_longest('abc', 'def')))
  354. self.assertEqual(len(dict.fromkeys(ids)), len(ids))
  355. def test_product(self):
  356. for args, result in [
  357. ([], [()]), # zero iterables
  358. (['ab'], [('a',), ('b',)]), # one iterable
  359. ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables
  360. ([range(0), range(2), range(3)], []), # first iterable with zero length
  361. ([range(2), range(0), range(3)], []), # middle iterable with zero length
  362. ([range(2), range(3), range(0)], []), # last iterable with zero length
  363. ]:
  364. self.assertEqual(list(product(*args)), result)
  365. for r in range(4):
  366. self.assertEqual(list(product(*(args*r))),
  367. list(product(*args, **dict(repeat=r))))
  368. self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
  369. self.assertRaises(TypeError, product, range(6), None)
  370. def product1(*args, **kwds):
  371. pools = map(tuple, args) * kwds.get('repeat', 1)
  372. n = len(pools)
  373. if n == 0:
  374. yield ()
  375. return
  376. if any(len(pool) == 0 for pool in pools):
  377. return
  378. indices = [0] * n
  379. yield tuple(pool[i] for pool, i in zip(pools, indices))
  380. while 1:
  381. for i in reversed(range(n)): # right to left
  382. if indices[i] == len(pools[i]) - 1:
  383. continue
  384. indices[i] += 1
  385. for j in range(i+1, n):
  386. indices[j] = 0
  387. yield tuple(pool[i] for pool, i in zip(pools, indices))
  388. break
  389. else:
  390. return
  391. def product2(*args, **kwds):
  392. 'Pure python version used in docs'
  393. pools = map(tuple, args) * kwds.get('repeat', 1)
  394. result = [[]]
  395. for pool in pools:
  396. result = [x+[y] for x in result for y in pool]
  397. for prod in result:
  398. yield tuple(prod)
  399. argtypes = ['', 'abc', '', xrange(0), xrange(4), dict(a=1, b=2, c=3),
  400. set('abcdefg'), range(11), tuple(range(13))]
  401. for i in range(100):
  402. args = [random.choice(argtypes) for j in range(random.randrange(5))]
  403. expected_len = prod(map(len, args))
  404. self.assertEqual(len(list(product(*args))), expected_len)
  405. self.assertEqual(list(product(*args)), list(product1(*args)))
  406. self.assertEqual(list(product(*args)), list(product2(*args)))
  407. args = map(iter, args)
  408. self.assertEqual(len(list(product(*args))), expected_len)
  409. # Test implementation detail: tuple re-use
  410. self.assertEqual(len(set(map(id, product('abc', 'def')))), 1)
  411. self.assertNotEqual(len(set(map(id, list(product('abc', 'def'))))), 1)
  412. def test_repeat(self):
  413. self.assertEqual(zip(xrange(3),repeat('a')),
  414. [(0, 'a'), (1, 'a'), (2, 'a')])
  415. self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
  416. self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
  417. self.assertEqual(list(repeat('a', 0)), [])
  418. self.assertEqual(list(repeat('a', -3)), [])
  419. self.assertRaises(TypeError, repeat)
  420. self.assertRaises(TypeError, repeat, None, 3, 4)
  421. self.assertRaises(TypeError, repeat, None, 'a')
  422. r = repeat(1+0j)
  423. self.assertEqual(repr(r), 'repeat((1+0j))')
  424. r = repeat(1+0j, 5)
  425. self.assertEqual(repr(r), 'repeat((1+0j), 5)')
  426. list(r)
  427. self.assertEqual(repr(r), 'repeat((1+0j), 0)')
  428. def test_imap(self):
  429. self.assertEqual(list(imap(operator.pow, range(3), range(1,7))),
  430. [0**1, 1**2, 2**3])
  431. self.assertEqual(list(imap(None, 'abc', range(5))),
  432. [('a',0),('b',1),('c',2)])
  433. self.assertEqual(list(imap(None, 'abc', count())),
  434. [('a',0),('b',1),('c',2)])
  435. self.assertEqual(take(2,imap(None, 'abc', count())),
  436. [('a',0),('b',1)])
  437. self.assertEqual(list(imap(operator.pow, [])), [])
  438. self.assertRaises(TypeError, imap)
  439. self.assertRaises(TypeError, imap, operator.neg)
  440. self.assertRaises(TypeError, imap(10, range(5)).next)
  441. self.assertRaises(ValueError, imap(errfunc, [4], [5]).next)
  442. self.assertRaises(TypeError, imap(onearg, [4], [5]).next)
  443. def test_starmap(self):
  444. self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
  445. [0**1, 1**2, 2**3])
  446. self.assertEqual(take(3, starmap(operator.pow, izip(count(), count(1)))),
  447. [0**1, 1**2, 2**3])
  448. self.assertEqual(list(starmap(operator.pow, [])), [])
  449. self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5])
  450. self.assertRaises(TypeError, list, starmap(operator.pow, [None]))
  451. self.assertRaises(TypeError, starmap)
  452. self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
  453. self.assertRaises(TypeError, starmap(10, [(4,5)]).next)
  454. self.assertRaises(ValueError, starmap(errfunc, [(4,5)]).next)
  455. self.assertRaises(TypeError, starmap(onearg, [(4,5)]).next)
  456. def test_islice(self):
  457. for args in [ # islice(args) should agree with range(args)
  458. (10, 20, 3),
  459. (10, 3, 20),
  460. (10, 20),
  461. (10, 3),
  462. (20,)
  463. ]:
  464. self.assertEqual(list(islice(xrange(100), *args)), range(*args))
  465. for args, tgtargs in [ # Stop when seqn is exhausted
  466. ((10, 110, 3), ((10, 100, 3))),
  467. ((10, 110), ((10, 100))),
  468. ((110,), (100,))
  469. ]:
  470. self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs))
  471. # Test stop=None
  472. self.assertEqual(list(islice(xrange(10), None)), range(10))
  473. self.assertEqual(list(islice(xrange(10), None, None)), range(10))
  474. self.assertEqual(list(islice(xrange(10), None, None, None)), range(10))
  475. self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10))
  476. self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
  477. # Test number of items consumed SF #1171417
  478. it = iter(range(10))
  479. self.assertEqual(list(islice(it, 3)), range(3))
  480. self.assertEqual(list(it), range(3, 10))
  481. # Test invalid arguments
  482. self.assertRaises(TypeError, islice, xrange(10))
  483. self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4)
  484. self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1)
  485. self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1)
  486. self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1)
  487. self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0)
  488. self.assertRaises(ValueError, islice, xrange(10), 'a')
  489. self.assertRaises(ValueError, islice, xrange(10), 'a', 1)
  490. self.assertRaises(ValueError, islice, xrange(10), 1, 'a')
  491. self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1)
  492. self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1)
  493. self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
  494. def test_takewhile(self):
  495. data = [1, 3, 5, 20, 2, 4, 6, 8]
  496. underten = lambda x: x<10
  497. self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
  498. self.assertEqual(list(takewhile(underten, [])), [])
  499. self.assertRaises(TypeError, takewhile)
  500. self.assertRaises(TypeError, takewhile, operator.pow)
  501. self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
  502. self.assertRaises(TypeError, takewhile(10, [(4,5)]).next)
  503. self.assertRaises(ValueError, takewhile(errfunc, [(4,5)]).next)
  504. t = takewhile(bool, [1, 1, 1, 0, 0, 0])
  505. self.assertEqual(list(t), [1, 1, 1])
  506. self.assertRaises(StopIteration, t.next)
  507. def test_dropwhile(self):
  508. data = [1, 3, 5, 20, 2, 4, 6, 8]
  509. underten = lambda x: x<10
  510. self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
  511. self.assertEqual(list(dropwhile(underten, [])), [])
  512. self.assertRaises(TypeError, dropwhile)
  513. self.assertRaises(TypeError, dropwhile, operator.pow)
  514. self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
  515. self.assertRaises(TypeError, dropwhile(10, [(4,5)]).next)
  516. self.assertRaises(ValueError, dropwhile(errfunc, [(4,5)]).next)
  517. def test_tee(self):
  518. n = 200
  519. def irange(n):
  520. for i in xrange(n):
  521. yield i
  522. a, b = tee([]) # test empty iterator
  523. self.assertEqual(list(a), [])
  524. self.assertEqual(list(b), [])
  525. a, b = tee(irange(n)) # test 100% interleaved
  526. self.assertEqual(zip(a,b), zip(range(n),range(n)))
  527. a, b = tee(irange(n)) # test 0% interleaved
  528. self.assertEqual(list(a), range(n))
  529. self.assertEqual(list(b), range(n))
  530. a, b = tee(irange(n)) # test dealloc of leading iterator
  531. for i in xrange(100):
  532. self.assertEqual(a.next(), i)
  533. del a
  534. self.assertEqual(list(b), range(n))
  535. a, b = tee(irange(n)) # test dealloc of trailing iterator
  536. for i in xrange(100):
  537. self.assertEqual(a.next(), i)
  538. del b
  539. self.assertEqual(list(a), range(100, n))
  540. for j in xrange(5): # test randomly interleaved
  541. order = [0]*n + [1]*n
  542. random.shuffle(order)
  543. lists = ([], [])
  544. its = tee(irange(n))
  545. for i in order:
  546. value = its[i].next()
  547. lists[i].append(value)
  548. self.assertEqual(lists[0], range(n))
  549. self.assertEqual(lists[1], range(n))
  550. # test argument format checking
  551. self.assertRaises(TypeError, tee)
  552. self.assertRaises(TypeError, tee, 3)
  553. self.assertRaises(TypeError, tee, [1,2], 'x')
  554. self.assertRaises(TypeError, tee, [1,2], 3, 'x')
  555. # tee object should be instantiable
  556. a, b = tee('abc')
  557. c = type(a)('def')
  558. self.assertEqual(list(c), list('def'))
  559. # test long-lagged and multi-way split
  560. a, b, c = tee(xrange(2000), 3)
  561. for i in xrange(100):
  562. self.assertEqual(a.next(), i)
  563. self.assertEqual(list(b), range(2000))
  564. self.assertEqual([c.next(), c.next()], range(2))
  565. self.assertEqual(list(a), range(100,2000))
  566. self.assertEqual(list(c), range(2,2000))
  567. # test values of n
  568. self.assertRaises(TypeError, tee, 'abc', 'invalid')
  569. self.assertRaises(ValueError, tee, [], -1)
  570. for n in xrange(5):
  571. result = tee('abc', n)
  572. self.assertEqual(type(result), tuple)
  573. self.assertEqual(len(result), n)
  574. self.assertEqual(map(list, result), [list('abc')]*n)
  575. # tee pass-through to copyable iterator
  576. a, b = tee('abc')
  577. c, d = tee(a)
  578. self.assert_(a is c)
  579. # test tee_new
  580. t1, t2 = tee('abc')
  581. tnew = type(t1)
  582. self.assertRaises(TypeError, tnew)
  583. self.assertRaises(TypeError, tnew, 10)
  584. t3 = tnew(t1)
  585. self.assert_(list(t1) == list(t2) == list(t3) == list('abc'))
  586. # test that tee objects are weak referencable
  587. a, b = tee(xrange(10))
  588. p = proxy(a)
  589. self.assertEqual(getattr(p, '__class__'), type(b))
  590. del a
  591. self.assertRaises(ReferenceError, getattr, p, '__class__')
  592. def test_StopIteration(self):
  593. self.assertRaises(StopIteration, izip().next)
  594. for f in (chain, cycle, izip, groupby):
  595. self.assertRaises(StopIteration, f([]).next)
  596. self.assertRaises(StopIteration, f(StopNow()).next)
  597. self.assertRaises(StopIteration, islice([], None).next)
  598. self.assertRaises(StopIteration, islice(StopNow(), None).next)
  599. p, q = tee([])
  600. self.assertRaises(StopIteration, p.next)
  601. self.assertRaises(StopIteration, q.next)
  602. p, q = tee(StopNow())
  603. self.assertRaises(StopIteration, p.next)
  604. self.assertRaises(StopIteration, q.next)
  605. self.assertRaises(StopIteration, repeat(None, 0).next)
  606. for f in (ifilter, ifilterfalse, imap, takewhile, dropwhile, starmap):
  607. self.assertRaises(StopIteration, f(lambda x:x, []).next)
  608. self.assertRaises(StopIteration, f(lambda x:x, StopNow()).next)
  609. class TestExamples(unittest.TestCase):
  610. def test_chain(self):
  611. self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF')
  612. def test_chain_from_iterable(self):
  613. self.assertEqual(''.join(chain.from_iterable(['ABC', 'DEF'])), 'ABCDEF')
  614. def test_combinations(self):
  615. self.assertEqual(list(combinations('ABCD', 2)),
  616. [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
  617. self.assertEqual(list(combinations(range(4), 3)),
  618. [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
  619. def test_count(self):
  620. self.assertEqual(list(islice(count(10), 5)), [10, 11, 12, 13, 14])
  621. def test_cycle(self):
  622. self.assertEqual(list(islice(cycle('ABCD'), 12)), list('ABCDABCDABCD'))
  623. def test_dropwhile(self):
  624. self.assertEqual(list(dropwhile(lambda x: x<5, [1,4,6,4,1])), [6,4,1])
  625. def test_groupby(self):
  626. self.assertEqual([k for k, g in groupby('AAAABBBCCDAABBB')],
  627. list('ABCDAB'))
  628. self.assertEqual([(list(g)) for k, g in groupby('AAAABBBCCD')],
  629. [list('AAAA'), list('BBB'), list('CC'), list('D')])
  630. def test_ifilter(self):
  631. self.assertEqual(list(ifilter(lambda x: x%2, range(10))), [1,3,5,7,9])
  632. def test_ifilterfalse(self):
  633. self.assertEqual(list(ifilterfalse(lambda x: x%2, range(10))), [0,2,4,6,8])
  634. def test_imap(self):
  635. self.assertEqual(list(imap(pow, (2,3,10), (5,2,3))), [32, 9, 1000])
  636. def test_islice(self):
  637. self.assertEqual(list(islice('ABCDEFG', 2)), list('AB'))
  638. self.assertEqual(list(islice('ABCDEFG', 2, 4)), list('CD'))
  639. self.assertEqual(list(islice('ABCDEFG', 2, None)), list('CDEFG'))
  640. self.assertEqual(list(islice('ABCDEFG', 0, None, 2)), list('ACEG'))
  641. def test_izip(self):
  642. self.assertEqual(list(izip('ABCD', 'xy')), [('A', 'x'), ('B', 'y')])
  643. def test_izip_longest(self):
  644. self.assertEqual(list(izip_longest('ABCD', 'xy', fillvalue='-')),
  645. [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')])
  646. def test_permutations(self):
  647. self.assertEqual(list(permutations('ABCD', 2)),
  648. map(tuple, 'AB AC AD BA BC BD CA CB CD DA DB DC'.split()))
  649. self.assertEqual(list(permutations(range(3))),
  650. [(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0)])
  651. def test_product(self):
  652. self.assertEqual(list(product('ABCD', 'xy')),
  653. map(tuple, 'Ax Ay Bx By Cx Cy Dx Dy'.split()))
  654. self.assertEqual(list(product(range(2), repeat=3)),
  655. [(0,0,0), (0,0,1), (0,1,0), (0,1,1),
  656. (1,0,0), (1,0,1), (1,1,0), (1,1,1)])
  657. def test_repeat(self):
  658. self.assertEqual(list(repeat(10, 3)), [10, 10, 10])
  659. def test_stapmap(self):
  660. self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])),
  661. [32, 9, 1000])
  662. def test_takewhile(self):
  663. self.assertEqual(list(takewhile(lambda x: x<5, [1,4,6,4,1])), [1,4])
  664. class TestGC(unittest.TestCase):
  665. def makecycle(self, iterator, container):
  666. container.append(iterator)
  667. iterator.next()
  668. del container, iterator
  669. def test_chain(self):
  670. a = []
  671. self.makecycle(chain(a), a)
  672. def test_chain_from_iterable(self):
  673. a = []
  674. self.makecycle(chain.from_iterable([a]), a)
  675. def test_combinations(self):
  676. a = []
  677. self.makecycle(combinations([1,2,a,3], 3), a)
  678. def test_cycle(self):
  679. a = []
  680. self.makecycle(cycle([a]*2), a)
  681. def test_dropwhile(self):
  682. a = []
  683. self.makecycle(dropwhile(bool, [0, a, a]), a)
  684. def test_groupby(self):
  685. a = []
  686. self.makecycle(groupby([a]*2, lambda x:x), a)
  687. def test_issue2246(self):
  688. # Issue 2246 -- the _grouper iterator was not included in GC
  689. n = 10
  690. keyfunc = lambda x: x
  691. for i, j in groupby(xrange(n), key=keyfunc):
  692. keyfunc.__dict__.setdefault('x',[]).append(j)
  693. def test_ifilter(self):
  694. a = []
  695. self.makecycle(ifilter(lambda x:True, [a]*2), a)
  696. def test_ifilterfalse(self):
  697. a = []
  698. self.makecycle(ifilterfalse(lambda x:False, a), a)
  699. def test_izip(self):
  700. a = []
  701. self.makecycle(izip([a]*2, [a]*3), a)
  702. def test_izip_longest(self):
  703. a = []
  704. self.makecycle(izip_longest([a]*2, [a]*3), a)
  705. b = [a, None]
  706. self.makecycle(izip_longest([a]*2, [a]*3, fillvalue=b), a)
  707. def test_imap(self):
  708. a = []
  709. self.makecycle(imap(lambda x:x, [a]*2), a)
  710. def test_islice(self):
  711. a = []
  712. self.makecycle(islice([a]*2, None), a)
  713. def test_permutations(self):
  714. a = []
  715. self.makecycle(permutations([1,2,a,3], 3), a)
  716. def test_product(self):
  717. a = []
  718. self.makecycle(product([1,2,a,3], repeat=3), a)
  719. def test_repeat(self):
  720. a = []
  721. self.makecycle(repeat(a), a)
  722. def test_starmap(self):
  723. a = []
  724. self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)
  725. def test_takewhile(self):
  726. a = []
  727. self.makecycle(takewhile(bool, [1, 0, a, a]), a)
  728. def R(seqn):
  729. 'Regular generator'
  730. for i in seqn:
  731. yield i
  732. class G:
  733. 'Sequence using __getitem__'
  734. def __init__(self, seqn):
  735. self.seqn = seqn
  736. def __getitem__(self, i):
  737. return self.seqn[i]
  738. class I:
  739. 'Sequence using iterator protocol'
  740. def __init__(self, seqn):
  741. self.seqn = seqn
  742. self.i = 0
  743. def __iter__(self):
  744. return self
  745. def next(self):
  746. if self.i >= len(self.seqn): raise StopIteration
  747. v = self.seqn[self.i]
  748. self.i += 1
  749. return v
  750. class Ig:
  751. 'Sequence using iterator protocol defined with a generator'
  752. def __init__(self, seqn):
  753. self.seqn = seqn
  754. self.i = 0
  755. def __iter__(self):
  756. for val in self.seqn:
  757. yield val
  758. class X:
  759. 'Missing __getitem__ and __iter__'
  760. def __init__(self, seqn):
  761. self.seqn = seqn
  762. self.i = 0
  763. def next(self):
  764. if self.i >= len(self.seqn): raise StopIteration
  765. v = self.seqn[self.i]
  766. self.i += 1
  767. return v
  768. class N:
  769. 'Iterator missing next()'
  770. def __init__(self, seqn):
  771. self.seqn = seqn
  772. self.i = 0
  773. def __iter__(self):
  774. return self
  775. class E:
  776. 'Test propagation of exceptions'
  777. def __init__(self, seqn):
  778. self.seqn = seqn
  779. self.i = 0
  780. def __iter__(self):
  781. return self
  782. def next(self):
  783. 3 // 0
  784. class S:
  785. 'Test immediate stop'
  786. def __init__(self, seqn):
  787. pass
  788. def __iter__(self):
  789. return self
  790. def next(self):
  791. raise StopIteration
  792. def L(seqn):
  793. 'Test multiple tiers of iterators'
  794. return chain(imap(lambda x:x, R(Ig(G(seqn)))))
  795. class TestVariousIteratorArgs(unittest.TestCase):
  796. def test_chain(self):
  797. for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
  798. for g in (G, I, Ig, S, L, R):
  799. self.assertEqual(list(chain(g(s))), list(g(s)))
  800. self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
  801. self.assertRaises(TypeError, list, chain(X(s)))
  802. self.assertRaises(TypeError, list, chain(N(s)))
  803. self.assertRaises(ZeroDivisionError, list, chain(E(s)))
  804. def test_product(self):
  805. for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
  806. self.assertRaises(TypeError, product, X(s))
  807. self.assertRaises(TypeError, product, N(s))
  808. self.assertRaises(ZeroDivisionError, product, E(s))
  809. def test_cycle(self):
  810. for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
  811. for g in (G, I, Ig, S, L, R):
  812. tgtlen = len(s) * 3
  813. expected = list(g(s))*3
  814. actual = list(islice(cycle(g(s)), tgtlen))
  815. self.assertEqual(actual, expected)
  816. self.assertRaises(TypeError, cycle, X(s))
  817. self.assertRaises(TypeError, list, cycle(N(s)))
  818. self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
  819. def test_groupby(self):
  820. for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
  821. for g in (G, I, Ig, S, L, R):
  822. self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
  823. self.assertRaises(TypeError, groupby, X(s))
  824. self.assertRaises(TypeError, list, groupby(N(s)))
  825. self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
  826. def test_ifilter(self):
  827. for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
  828. for g in (G, I, Ig, S, L, R):
  829. self.assertEqual(list(ifilter(isEven, g(s))), filter(isEven, g(s)))
  830. self.assertRaises(TypeError, ifilter, isEven, X(s))
  831. self.assertRaises(TypeError, list, ifilter(isEven, N(s)))
  832. self.assertRaises(ZeroDivisionError, list, ifilter(isEven, E(s)))
  833. def test_ifilterfalse(self):
  834. for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
  835. for g in (G, I, Ig, S, L, R):
  836. self.assertEqual(list(ifilterfalse(isEven, g(s))), filter(isOdd, g(s)))
  837. self.assertRaises(TypeError, ifilterfalse, isEven, X(s))
  838. self.assertRaises(TypeError, list, ifilterfalse(isEven, N(s)))
  839. self.assertRaises(ZeroDivisionError, list, ifilterfalse(isEven, E(s)))
  840. def test_izip(self):
  841. for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
  842. for g in (G, I, Ig, S, L, R):
  843. self.assertEqual(list(izip(g(s))), zip(g(s)))
  844. self.assertEqual(list(izip(g(s), g(s))), zip(g(s), g(s)))
  845. self.assertRaises(TypeError, izip, X(s))
  846. self.assertRaises(TypeError, list, izip(N(s)))
  847. self.assertRaises(ZeroDivisionError, list, izip(E(s)))
  848. def test_iziplongest(self):
  849. for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
  850. for g in (G, I, Ig, S, L, R):
  851. self.assertEqual(list(izip_longest(g(s))), zip(g(s)))
  852. self.assertEqual(list(izip_longest(g(s), g(s))), zip(g(s), g(s)))
  853. self.assertRaises(TypeError, izip_longest, X(s))
  854. self.assertRaises(TypeError, list, izip_longest(N(s)))
  855. self.assertRaises(ZeroDivisionError, list, izip_longest(E(s)))
  856. def test_imap(self):
  857. for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
  858. for g in (G, I, Ig, S, L, R):
  859. self.assertEqual(list(imap(onearg, g(s))), map(onearg, g(s)))
  860. self.assertEqual(list(imap(operator.pow, g(s), g(s))), map(operator.pow, g(s), g(s)))
  861. self.assertRaises(TypeError, imap, onearg, X(s))
  862. self.assertRaises(TypeError, list, imap(onearg, N(s)))
  863. self.assertRaises(ZeroDivisionError, list, imap(onearg, E(s)))
  864. def test_islice(self):
  865. for s in ("12345", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
  866. for g in (G, I, Ig, S, L, R):
  867. self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
  868. self.assertRaises(TypeError, islice, X(s), 10)
  869. self.assertRaises(TypeError, list, islice(N(s), 10))
  870. self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
  871. def test_starmap(self):
  872. for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
  873. for g in (G, I, Ig, S, L, R):
  874. ss = zip(s, s)
  875. self.assertEqual(list(starmap(operator.pow, g(ss))), map(operator.pow, g(s), g(s)))
  876. self.assertRaises(TypeError, starmap, operator.pow, X(ss))
  877. self.assertRaises(TypeError, list, starmap(operator.pow, N(ss)))
  878. self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
  879. def test_takewhile(self):
  880. for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
  881. for g in (G, I, Ig, S, L, R):
  882. tgt = []
  883. for elem in g(s):
  884. if not isEven(elem): break
  885. tgt.append(elem)
  886. self.assertEqual(list(takewhile(isEven, g(s))), tgt)
  887. self.assertRaises(TypeError, takewhile, isEven, X(s))
  888. self.assertRaises(TypeError, list, takewhile(isEven, N(s)))
  889. self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
  890. def test_dropwhile(self):
  891. for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
  892. for g in (G, I, Ig, S, L, R):
  893. tgt = []
  894. for elem in g(s):
  895. if not tgt and isOdd(elem): continue
  896. tgt.append(elem)
  897. self.assertEqual(list(dropwhile(isOdd, g(s))), tgt)
  898. self.assertRaises(TypeError, dropwhile, isOdd, X(s))
  899. self.assertRaises(TypeError, list, dropwhile(isOdd, N(s)))
  900. self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
  901. def test_tee(self):
  902. for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
  903. for g in (G, I, Ig, S, L, R):
  904. it1, it2 = tee(g(s))
  905. self.assertEqual(list(it1), list(g(s)))
  906. self.assertEqual(list(it2), list(g(s)))
  907. self.assertRaises(TypeError, tee, X(s))
  908. self.assertRaises(TypeError, list, tee(N(s))[0])
  909. self.assertRaises(ZeroDivisionError, list, tee(E(s))[0])
  910. class LengthTransparency(unittest.TestCase):
  911. def test_repeat(self):
  912. from test.test_iterlen import len
  913. self.assertEqual(len(repeat(None, 50)), 50)
  914. self.assertRaises(TypeError, len, repeat(None))
  915. class RegressionTests(unittest.TestCase):
  916. def test_sf_793826(self):
  917. # Fix Armin Rigo's successful efforts to wreak havoc
  918. def mutatingtuple(tuple1, f, tuple2):
  919. # this builds a tuple t which is a copy of tuple1,
  920. # then calls f(t), then mutates t to be equal to tuple2
  921. # (needs len(tuple1) == len(tuple2)).
  922. def g(value, first=[1]):
  923. if first:
  924. del first[:]
  925. f(z.next())
  926. return value
  927. items = list(tuple2)
  928. items[1:1] = list(tuple1)
  929. gen = imap(g, items)
  930. z = izip(*[gen]*len(tuple1))
  931. z.next()
  932. def f(t):
  933. global T
  934. T = t
  935. first[:] = list(T)
  936. first = []
  937. mutatingtuple((1,2,3), f, (4,5,6))
  938. second = list(T)
  939. self.assertEqual(first, second)
  940. def test_sf_950057(self):
  941. # Make sure that chain() and cycle() catch exceptions immediately
  942. # rather than when shifting between input sources
  943. def gen1():
  944. hist.append(0)
  945. yield 1
  946. hist.append(1)
  947. raise AssertionError
  948. hist.append(2)
  949. def gen2(x):
  950. hist.append(3)
  951. yield 2
  952. hist.append(4)
  953. if x:
  954. raise StopIteration
  955. hist = []
  956. self.assertRaises(AssertionError, list, chain(gen1(), gen2(False)))
  957. self.assertEqual(hist, [0,1])
  958. hist = []
  959. self.assertRaises(AssertionError, list, chain(gen1(), gen2(True)))
  960. self.assertEqual(hist, [0,1])
  961. hist = []
  962. self.assertRaises(AssertionError, list, cycle(gen1()))
  963. self.assertEqual(hist, [0,1])
  964. class SubclassWithKwargsTest(unittest.TestCase):
  965. def test_keywords_in_subclass(self):
  966. # count is not subclassable...
  967. for cls in (repeat, izip, ifilter, ifilterfalse, chain, imap,
  968. starmap, islice, takewhile, dropwhile, cycle):
  969. class Subclass(cls):
  970. def __init__(self, newarg=None, *args):
  971. cls.__init__(self, *args)
  972. try:
  973. Subclass(newarg=1)
  974. except TypeError, err:
  975. # we expect type errors because of wrong argument count
  976. self.failIf("does not take keyword arguments" in err.args[0])
  977. libreftest = """ Doctest for examples in the library reference: libitertools.tex
  978. >>> amounts = [120.15, 764.05, 823.14]
  979. >>> for checknum, amount in izip(count(1200), amounts):
  980. ... print 'Check %d is for $%.2f' % (checknum, amount)
  981. ...
  982. Check 1200 is for $120.15
  983. Check 1201 is for $764.05
  984. Check 1202 is for $823.14
  985. >>> import operator
  986. >>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
  987. ... print cube
  988. ...
  989. 1
  990. 8
  991. 27
  992. >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
  993. >>> for name in islice(reportlines, 3, None, 2):
  994. ... print name.title()
  995. ...
  996. Alex
  997. Laura
  998. Martin
  999. Walter
  1000. Samuele
  1001. >>> from operator import itemgetter
  1002. >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
  1003. >>> di = sorted(sorted(d.iteritems()), key=itemgetter(1))
  1004. >>> for k, g in groupby(di, itemgetter(1)):
  1005. ... print k, map(itemgetter(0), g)
  1006. ...
  1007. 1 ['a', 'c', 'e']
  1008. 2 ['b', 'd', 'f']
  1009. 3 ['g']
  1010. # Find runs of consecutive numbers using groupby. The key to the solution
  1011. # is differencing with a range so that consecutive numbers all appear in
  1012. # same group.
  1013. >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
  1014. >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x):
  1015. ... print map(operator.itemgetter(1), g)
  1016. ...
  1017. [1]
  1018. [4, 5, 6]
  1019. [10]
  1020. [15, 16, 17, 18]
  1021. [22]
  1022. [25, 26, 27, 28]
  1023. >>> def take(n, iterable):
  1024. ... "Return first n items of the iterable as a list"
  1025. ... return list(islice(iterable, n))
  1026. >>> def enumerate(iterable, start=0):
  1027. ... return izip(count(start), iterable)
  1028. >>> def tabulate(function, start=0):
  1029. ... "Return function(0), function(1), ..."
  1030. ... return imap(function, count(start))
  1031. >>> def nth(iterable, n, default=None):
  1032. ... "Returns the nth item or a default value"
  1033. ... return next(islice(iterable, n, None), default)
  1034. >>> def quantify(iterable, pred=bool):
  1035. ... "Count how many times the predicate is true"
  1036. ... return sum(imap(pred, iterable))
  1037. >>> def padnone(iterable):
  1038. ... "Returns the sequence elements and then returns None indefinitely"
  1039. ... return chain(iterable, repeat(None))
  1040. >>> def ncycles(iterable, n):
  1041. ... "Returns the seqeuence elements n times"
  1042. ... return chain(*repeat(iterable, n))
  1043. >>> def dotproduct(vec1, vec2):
  1044. ... return sum(imap(operator.mul, vec1, vec2))
  1045. >>> def flatten(listOfLists):
  1046. ... return list(chain.from_iterable(listOfLists))
  1047. >>> def repeatfunc(func, times=None, *args):
  1048. ... "Repeat calls to func with specified arguments."
  1049. ... " Example: repeatfunc(random.random)"
  1050. ... if times is None:
  1051. ... return starmap(func, repeat(args))
  1052. ... else:
  1053. ... return starmap(func, repeat(args, times))
  1054. >>> def pairwise(iterable):
  1055. ... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
  1056. ... a, b = tee(iterable)
  1057. ... for elem in b:
  1058. ... break
  1059. ... return izip(a, b)
  1060. >>> def grouper(n, iterable, fillvalue=None):
  1061. ... "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
  1062. ... args = [iter(iterable)] * n
  1063. ... return izip_longest(fillvalue=fillvalue, *args)
  1064. >>> def roundrobin(*iterables):
  1065. ... "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
  1066. ... # Recipe credited to George Sakkis
  1067. ... pending = len(iterables)
  1068. ... nexts = cycle(iter(it).next for it in iterables)
  1069. ... while pending:
  1070. ... try:
  1071. ... for next in nexts:
  1072. ... yield next()
  1073. ... except StopIteration:
  1074. ... pending -= 1
  1075. ... nexts = cycle(islice(nexts, pending))
  1076. >>> def powerset(iterable):
  1077. ... "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
  1078. ... s = list(iterable)
  1079. ... return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
  1080. >>> def compress(data, selectors):
  1081. ... "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"
  1082. ... return (d for d, s in izip(data, selectors) if s)
  1083. >>> def combinations_with_replacement(iterable, r):
  1084. ... "combinations_with_replacement('ABC', 3) --> AA AB AC BB BC CC"
  1085. ... pool = tuple(iterable)
  1086. ... n = len(pool)
  1087. ... if not n and r:
  1088. ... return
  1089. ... indices = [0] * r
  1090. ... yield tuple(pool[i] for i in indices)
  1091. ... while 1:
  1092. ... for i in reversed(range(r)):
  1093. ... if indices[i] != n - 1:
  1094. ... break
  1095. ... else:
  1096. ... return
  1097. ... indices[i:] = [indices[i] + 1] * (r - i)
  1098. ... yield tuple(pool[i] for i in indices)
  1099. >>> def unique_everseen(iterable, key=None):
  1100. ... "List unique elements, preserving order. Remember all elements ever seen."
  1101. ... # unique_everseen('AAAABBBCCDAABBB') --> A B C D
  1102. ... # unique_everseen('ABBCcAD', str.lower) --> A B C D
  1103. ... seen = set()
  1104. ... seen_add = seen.add
  1105. ... if key is None:
  1106. ... for element in iterable:
  1107. ... if element not in seen:
  1108. ... seen_add(element)
  1109. ... yield element
  1110. ... else:
  1111. ... for element in iterable:
  1112. ... k = key(element)
  1113. ... if k not in seen:
  1114. ... seen_add(k)
  1115. ... yield element
  1116. >>> def unique_justseen(iterable, key=None):
  1117. ... "List unique elements, preserving order. Remember only the element just seen."
  1118. ... # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
  1119. ... # unique_justseen('ABBCcAD', str.lower) --> A B C A D
  1120. ... return imap(next, imap(itemgetter(1), groupby(iterable, key)))
  1121. This is not part of the examples but it tests to make sure the definitions
  1122. perform as purported.
  1123. >>> take(10, count())
  1124. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1125. >>> list(enumerate('abc'))
  1126. [(0, 'a'), (1, 'b'), (2, 'c')]
  1127. >>> list(islice(tabulate(lambda x: 2*x), 4))
  1128. [0, 2, 4, 6]
  1129. >>> nth('abcde', 3)
  1130. 'd'
  1131. >>> nth('abcde', 9) is None
  1132. True
  1133. >>> quantify(xrange(99), lambda x: x%2==0)
  1134. 50
  1135. >>> a = [[1, 2, 3], [4, 5, 6]]
  1136. >>> flatten(a)
  1137. [1, 2, 3, 4, 5, 6]
  1138. >>> list(repeatfunc(pow, 5, 2, 3))
  1139. [8, 8, 8, 8, 8]
  1140. >>> import random
  1141. >>> take(5, imap(int, repeatfunc(random.random)))
  1142. [0, 0, 0, 0, 0]
  1143. >>> list(pairwise('abcd'))
  1144. [('a', 'b'), ('b', 'c'), ('c', 'd')]
  1145. >>> list(pairwise([]))
  1146. []
  1147. >>> list(pairwise('a'))
  1148. []
  1149. >>> list(islice(padnone('abc'), 0, 6))
  1150. ['a', 'b', 'c', None, None, None]
  1151. >>> list(ncycles('abc', 3))
  1152. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
  1153. >>> dotproduct([1,2,3], [4,5,6])
  1154. 32
  1155. >>> list(grouper(3, 'abcdefg', 'x'))
  1156. [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x')]
  1157. >>> list(roundrobin('abc', 'd', 'ef'))
  1158. ['a', 'd', 'e', 'b', 'f', 'c']
  1159. >>> list(powerset([1,2,3]))
  1160. [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
  1161. >>> list(compress('abcdef', [1,0,1,0,1,1]))
  1162. ['a', 'c', 'e', 'f']
  1163. >>> list(combinations_with_replacement('abc', 2))
  1164. [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]
  1165. >>> list(combinations_with_replacement('01', 3))
  1166. [('0', '0', '0'), ('0', '0', '1'), ('0', '1', '1'), ('1', '1', '1')]
  1167. >>> def combinations_with_replacement2(iterable, r):
  1168. ... 'Alternate version that filters from product()'
  1169. ... pool = tuple(iterable)
  1170. ... n = len(pool)
  1171. ... for indices in product(range(n), repeat=r):
  1172. ... if sorted(indices) == list(indices):
  1173. ... yield tuple(pool[i] for i in indices)
  1174. >>> list(combinations_with_replacement('abc', 2)) == list(combinations_with_replacement2('abc', 2))
  1175. True
  1176. >>> list(combinations_with_replacement('01', 3)) == list(combinations_with_replacement2('01', 3))
  1177. True
  1178. >>> list(combinations_with_replacement('2310', 6)) == list(combinations_with_replacement2('2310', 6))
  1179. True
  1180. >>> list(unique_everseen('AAAABBBCCDAABBB'))
  1181. ['A', 'B', 'C', 'D']
  1182. >>> list(unique_everseen('ABBCcAD', str.lower))
  1183. ['A', 'B', 'C', 'D']
  1184. >>> list(unique_justseen('AAAABBBCCDAABBB'))
  1185. ['A', 'B', 'C', 'D', 'A', 'B']
  1186. >>> list(unique_justseen('ABBCcAD', str.lower))
  1187. ['A', 'B', 'C', 'A', 'D']
  1188. """
  1189. __test__ = {'libreftest' : libreftest}
  1190. def test_main(verbose=None):
  1191. test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC,
  1192. RegressionTests, LengthTransparency,
  1193. SubclassWithKwargsTest, TestExamples)
  1194. test_support.run_unittest(*test_classes)
  1195. # verify reference counting
  1196. if verbose and hasattr(sys, "gettotalrefcount"):
  1197. import gc
  1198. counts = [None] * 5
  1199. for i in xrange(len(counts)):
  1200. test_support.run_unittest(*test_classes)
  1201. gc.collect()
  1202. counts[i] = sys.gettotalrefcount()
  1203. print counts
  1204. # doctest the examples in the library reference
  1205. test_support.run_doctest(sys.modules[__name__], verbose)
  1206. if __name__ == "__main__":
  1207. test_main(verbose=True)