run the test three times first verify that a deprecation warning is raised second run normally but with deprecationwarnings temporarily disabled third run with warnings promoted to errors root level methods for pickling ability test that an iterator is the same after pickling also when partconsumed def expandit i0 recursively expand iterables within sensible bounds if i 10 raise runtimeerrorinfinite recursion encountered if isinstanceit str return it try l listisliceit stop except typeerror return it can t expand it return expande i1 for e in l test the initial copy against the original dump pickle dumpsit protocol i2 pickle loadsdump self assertequaltypeit typei2 a b expandit expandi2 self assertequala b if compare c expandcompare self assertequala c take from the copy and create another copy and compare them i3 pickle loadsdump took 0 try for i in rangetake nexti3 took 1 except stopiteration pass in case there is less data than take dump pickle dumpsi3 protocol i4 pickle loadsdump a b expandi3 expandi4 self assertequala b if compare c expandcomparetook self assertequala c pickledeprecated def testaccumulateself self assertequallistaccumulaterange10 one positional arg 0 1 3 6 10 15 21 28 36 45 self assertequallistaccumulateiterablerange10 kw arg 0 1 3 6 10 15 21 28 36 45 for typ in int complex decimal fraction multiple types self assertequal listaccumulatemaptyp range10 listmaptyp 0 1 3 6 10 15 21 28 36 45 self assertequallistaccumulate abc a ab abc works with nonnumeric self assertequallistaccumulate empty iterable self assertequallistaccumulate7 7 iterable of length one self assertraisestypeerror accumulate range10 5 6 too many args self assertraisestypeerror accumulate too few args self assertraisestypeerror accumulate xrange10 unexpected kwd arg self assertraisestypeerror list accumulate1 args that don t add s 2 8 9 5 7 0 3 4 1 6 self assertequallistaccumulates min 2 2 2 2 2 0 0 0 0 0 self assertequallistaccumulates max 2 8 9 9 9 9 9 9 9 9 self assertequallistaccumulates operator mul 2 16 144 720 5040 0 0 0 0 0 with self assertraisestypeerror listaccumulates chr unaryoperation for proto in rangepickle highestprotocol 1 self pickletestproto accumulaterange10 test pickling self pickletestproto accumulaterange10 initial7 self assertequallistaccumulate10 5 1 initialnone 10 15 16 self assertequallistaccumulate10 5 1 initial100 100 110 115 116 self assertequallistaccumulate initial100 100 with self assertraisestypeerror listaccumulate10 20 100 def testbatchedself self assertequallistbatched abcdefg 3 a b c d e f g self assertequallistbatched abcdefg 2 a b c d e f g self assertequallistbatched abcdefg 1 a b c d e f g with self assertraisestypeerror too few arguments listbatched abcdefg with self assertraisestypeerror listbatched abcdefg 3 none too many arguments with self assertraisestypeerror listbatchednone 3 noniterable input with self assertraisestypeerror listbatched abcdefg hello n is a string with self assertraisesvalueerror listbatched abcdefg 0 n is zero with self assertraisesvalueerror listbatched abcdefg 1 n is negative data abcdefghijklmnopqrstuvwxyz for n in range1 6 for i in rangelendata s data i batches listbatcheds n with self subtestss nn batchesbatches order is preserved and no data is lost self assertequal joinchainbatches s each batch is an exact tuple self asserttruealltypebatch is tuple for batch in batches all but the last batch is of size n if batches lastbatch batches pop self asserttruealllenbatch n for batch in batches self asserttruelenlastbatch n batches appendlastbatch def testchainself def chain2iterables pure python version in the docs for it in iterables for element in it yield element for c in chain chain2 self assertequallistc abc def list abcdef self assertequallistc abc list abc self assertequallistc self assertequaltake4 c abc def list abcd self assertraisestypeerror list c2 3 def testchainfromiterableself self assertequallistchain fromiterable abc def list abcdef self assertequallistchain fromiterable abc list abc self assertequallistchain fromiterable self assertequaltake4 chain fromiterable abc def list abcd self assertraisestypeerror list chain fromiterable2 3 self assertequallistislicechain fromiterablerepeatrange5 2 0 1 pickledeprecated def testchainreducibleself for oper in copy deepcopy picklecopiers it chain abc def self assertequallistoperit list abcdef self assertequalnextit a self assertequallistoperit list bcdef self assertequallistoperchain self assertequaltake4 operchain abc def list abcd self assertraisestypeerror list operchain2 3 for proto in rangepickle highestprotocol 1 self pickletestproto chain abc def comparelist abcdef pickledeprecated def testchainsetstateself self assertraisestypeerror chain setstate self assertraisestypeerror chain setstate self assertraisestypeerror chain setstate 0 self assertraisestypeerror chain setstate self assertraisestypeerror chain setstate iter it chain it setstateiter abc def self assertequallistit a b c d e f it chain it setstateiter abc def iter ghi self assertequallistit ghi a b c d e f pickledeprecated def testcombinationsself self assertraisestypeerror combinations abc missing r argument self assertraisestypeerror combinations abc 2 1 too many arguments self assertraisestypeerror combinations none pool is not iterable self assertraisesvalueerror combinations abc 2 r is negative for op in lambda a a picklecopiers self assertequallistopcombinations abc 32 r n self assertequallistopcombinations abcd 2 a b a c a d b c b d c d testintermediate combinations abcd 2 nexttestintermediate self assertequallistoptestintermediate a c a d b c b d c d self assertequallistopcombinationsrange4 3 0 1 2 0 1 3 0 2 3 1 2 3 testintermediate combinationsrange4 3 nexttestintermediate self assertequallistoptestintermediate 0 1 3 0 2 3 1 2 3 def combinations1iterable r pure python version shown in the docs pool tupleiterable n lenpool if r n return indices listranger yield tuplepooli for i in indices while 1 for i in reversedranger if indicesi i n r break else return indicesi 1 for j in rangei1 r indicesj indicesj1 1 yield tuplepooli for i in indices def combinations2iterable r pure python version shown in the docs pool tupleiterable n lenpool for indices in permutationsrangen r if sortedindices listindices yield tuplepooli for i in indices def combinations3iterable r pure python version from cwr pool tupleiterable n lenpool for indices in combinationswithreplacementrangen r if lensetindices r yield tuplepooli for i in indices for n in range7 values 5x12 for x in rangen for r in rangen2 result listcombinationsvalues r self assertequallenresult 0 if rn else factn factr factnr right number of combs self assertequallenresult lensetresult no repeats self assertequalresult sortedresult lexicographic order for c in result self assertequallenc r rlength combinations self assertequallensetc r no duplicate elements self assertequallistc sortedc keep original ordering self asserttruealle in values for e in c elements taken from input iterable self assertequallistc e for e in values if e in c comb is a subsequence of the input iterable self assertequalresult listcombinations1values r matches first pure python version self assertequalresult listcombinations2values r matches second pure python version self assertequalresult listcombinations3values r matches second pure python version for proto in rangepickle highestprotocol 1 self pickletestproto combinationsvalues r test pickling support bigaddrspacetest def testcombinationsoverflowself with self assertraisesoverflowerror memoryerror combinationsaa 229 test implementation detail tuple reuse support impldetailtuple reuse is specific to cpython def testcombinationstuplereuseself self assertequallensetmapid combinations abcde 3 1 self assertnotequallensetmapid listcombinations abcde 3 1 pickledeprecated def testcombinationswithreplacementself cwr combinationswithreplacement self assertraisestypeerror cwr abc missing r argument self assertraisestypeerror cwr abc 2 1 too many arguments self assertraisestypeerror cwr none pool is not iterable self assertraisesvalueerror cwr abc 2 r is negative for op in lambda a a picklecopiers self assertequallistopcwr abc 2 a a a b a c b b b c c c testintermediate cwr abc 2 nexttestintermediate self assertequallistoptestintermediate a b a c b b b c c c def cwr1iterable r pure python version shown in the docs number items returned nr1 r n1 when n0 pool tupleiterable n lenpool if not n and r return indices 0 r yield tuplepooli for i in indices while 1 for i in reversedranger if indicesi n 1 break else return indicesi indicesi 1 r i yield tuplepooli for i in indices def cwr2iterable r pure python version shown in the docs pool tupleiterable n lenpool for indices in productrangen repeatr if sortedindices listindices yield tuplepooli for i in indices def numcombsn r if not n return 0 if r else 1 return factnr1 factr factn1 for n in range7 values 5x12 for x in rangen for r in rangen2 result listcwrvalues r self assertequallenresult numcombsn r right number of combs self assertequallenresult lensetresult no repeats self assertequalresult sortedresult lexicographic order regularcombs listcombinationsvalues r compare to combs without replacement if n 0 or r 1 self assertequalresult regularcombs cases that should be identical else self asserttruesetresult setregularcombs rest should be supersets of regular combs for c in result self assertequallenc r rlength combinations noruns k for k v in groupbyc combo without consecutive repeats self assertequallennoruns lensetnoruns no repeats other than consecutive self assertequallistc sortedc keep original ordering self asserttruealle in values for e in c elements taken from input iterable self assertequalnoruns e for e in values if e in c comb is a subsequence of the input iterable self assertequalresult listcwr1values r matches first pure python version self assertequalresult listcwr2values r matches second pure python version for proto in rangepickle highestprotocol 1 self pickletestproto cwrvalues r test pickling support bigaddrspacetest def testcombinationswithreplacementoverflowself with self assertraisesoverflowerror memoryerror combinationswithreplacementaa 230 test implementation detail tuple reuse support impldetailtuple reuse is specific to cpython def testcombinationswithreplacementtuplereuseself cwr combinationswithreplacement self assertequallensetmapid cwr abcde 3 1 self assertnotequallensetmapid listcwr abcde 3 1 pickledeprecated def testpermutationsself self assertraisestypeerror permutations too few arguments self assertraisestypeerror permutations abc 2 1 too many arguments self assertraisestypeerror permutations none pool is not iterable self assertraisesvalueerror permutations abc 2 r is negative self assertequallistpermutations abc 32 r n self assertraisestypeerror permutations abc s r is not an int or none self assertequallistpermutationsrange3 2 0 1 0 2 1 0 1 2 2 0 2 1 def permutations1iterable rnone pure python version shown in the docs pool tupleiterable n lenpool r n if r is none else r if r n return indices listrangen cycles listrangenr1 n1 1 yield tuplepooli for i in indices r while n for i in reversedranger cyclesi 1 if cyclesi 0 indicesi indicesi1 indicesi i1 cyclesi n i else j cyclesi indicesi indicesj indicesj indicesi yield tuplepooli for i in indices r break else return def permutations2iterable rnone pure python version shown in the docs pool tupleiterable n lenpool r n if r is none else r for indices in productrangen repeatr if lensetindices r yield tuplepooli for i in indices for n in range7 values 5x12 for x in rangen for r in rangen2 result listpermutationsvalues r self assertequallenresult 0 if rn else factn factnr right number of perms self assertequallenresult lensetresult no repeats self assertequalresult sortedresult lexicographic order for p in result self assertequallenp r rlength permutations self assertequallensetp r no duplicate elements self asserttruealle in values for e in p elements taken from input iterable self assertequalresult listpermutations1values r matches first pure python version self assertequalresult listpermutations2values r matches second pure python version if r n self assertequalresult listpermutationsvalues none test r as none self assertequalresult listpermutationsvalues test default r for proto in rangepickle highestprotocol 1 self pickletestproto permutationsvalues r test pickling support bigaddrspacetest def testpermutationsoverflowself with self assertraisesoverflowerror memoryerror permutationsa 230 support impldetailtuple reuse is specific to cpython def testpermutationstuplereuseself self assertequallensetmapid permutations abcde 3 1 self assertnotequallensetmapid listpermutations abcde 3 1 def testcombinatoricsself test relationships between product permutations combinations and combinationswithreplacement for n in range6 s abcdefg n for r in range8 prod listproducts repeatr cwr listcombinationswithreplacements r perm listpermutationss r comb listcombinationss r check size self assertequallenprod nr self assertequallencwr factnr1 factr factn1 if n else not r self assertequallenperm 0 if rn else factn factnr self assertequallencomb 0 if rn else factn factr factnr check lexicographic order without repeated tuples self assertequalprod sortedsetprod self assertequalcwr sortedsetcwr self assertequalperm sortedsetperm self assertequalcomb sortedsetcomb check interrelationships self assertequalcwr t for t in prod if sortedtlistt cwr prods which are sorted self assertequalperm t for t in prod if lensettr perm prods with no dups self assertequalcomb t for t in perm if sortedtlistt comb perms that are sorted self assertequalcomb t for t in cwr if lensettr comb cwrs without dups self assertequalcomb listfiltersetcwr contains perm comb perm that is a cwr self assertequalcomb listfiltersetperm contains cwr comb cwr that is a perm self assertequalcomb sortedsetcwr setperm comb both a cwr and a perm pickledeprecated def testcompressself self assertequallistcompressdata abcdef selectors1 0 1 0 1 1 list acef self assertequallistcompress abcdef 1 0 1 0 1 1 list acef self assertequallistcompress abcdef 0 0 0 0 0 0 list self assertequallistcompress abcdef 1 1 1 1 1 1 list abcdef self assertequallistcompress abcdef 1 0 1 list ac self assertequallistcompress abc 0 1 1 1 1 1 list bc n 10000 data chain fromiterablerepeatrange6 n selectors chain fromiterablerepeat0 1 self assertequallistcompressdata selectors 1 3 5 n self assertraisestypeerror compress none range6 1st arg not iterable self assertraisestypeerror compress range6 none 2nd arg not iterable self assertraisestypeerror compress range6 too few args self assertraisestypeerror compress range6 none too many args check copy deepcopy pickle for op in lambda a copy copya lambda a copy deepcopya picklecopiers for data selectors result1 result2 in abcdef 1 0 1 0 1 1 acef cef abcdef 0 0 0 0 0 0 abcdef 1 1 1 1 1 1 abcdef bcdef abcdef 1 0 1 ac c abc 0 1 1 1 1 1 bc c self assertequallistopcompressdatadata selectorsselectors listresult1 self assertequallistopcompressdata selectors listresult1 testintermediate compressdata selectors if result1 nexttestintermediate self assertequallistoptestintermediate listresult2 pickledeprecated def testcountself self assertequallzip abc count a 0 b 1 c 2 self assertequallzip abc count3 a 3 b 4 c 5 self assertequaltake2 lzip abc count3 a 3 b 4 self assertequaltake2 zip abc count1 a 1 b 0 self assertequaltake2 zip abc count3 a 3 b 2 self assertraisestypeerror count 2 3 4 self assertraisestypeerror count a self assertequaltake10 countmaxsize5 listrangemaxsize5 maxsize5 self assertequaltake10 countmaxsize5 listrangemaxsize5 maxsize5 self assertequaltake3 count3 25 3 25 4 25 5 25 self assertequaltake3 count3 254j 3 254j 4 254j 5 254j self assertequaltake3 countdecimal 1 1 decimal 1 1 decimal 2 1 decimal 3 1 self assertequaltake3 countfraction2 3 fraction2 3 fraction5 3 fraction8 3 bigint 11000 self assertequaltake3 countbigint bigint bigint1 bigint2 c count3 self assertequalreprc count3 nextc self assertequalreprc count4 c count9 self assertequalreprc count9 nextc self assertequalnextc 8 self assertequalreprcount10 25 count10 25 self assertequalreprcount10 0 count10 0 self assertequaltypenextcount10 0 float for i in sys maxsize5 sys maxsize5 10 1 0 10 sys maxsize5 sys maxsize5 test repr r1 reprcounti r2 countr modi self assertequalr1 r2 check copy deepcopy pickle for value in 3 3 maxsize5 maxsize5 c countvalue self assertequalnextcopy copyc value self assertequalnextcopy deepcopyc value for proto in rangepickle highestprotocol 1 self pickletestproto countvalue check proper internal error handling for large step sizes count1 maxsize5 sys excinfo pickledeprecated def testcountwithstrideself self assertequallzip abc count2 3 a 2 b 5 c 8 self assertequallzip abc countstart2 step3 a 2 b 5 c 8 self assertequallzip abc countstep1 a 0 b 1 c 2 self assertraisestypeerror count a b self assertequallzip abc count2 0 a 2 b 2 c 2 self assertequallzip abc count2 1 a 2 b 3 c 4 self assertequallzip abc count2 3 a 2 b 5 c 8 self assertequaltake20 countmaxsize15 3 take20 rangemaxsize15 maxsize100 3 self assertequaltake20 countmaxsize15 3 take20 rangemaxsize15 maxsize100 3 self assertequaltake3 count10 maxsize5 listrange10 103maxsize5 maxsize5 self assertequaltake3 count2 1 25 2 3 25 4 5 self assertequaltake3 count2 3 254j 2 5 254j 8 58j self assertequaltake3 countdecimal 1 1 decimal 1 decimal 1 1 decimal 1 2 decimal 1 3 self assertequaltake3 countfraction2 3 fraction1 7 fraction2 3 fraction17 21 fraction20 21 bigint 11000 self assertequaltake3 countstepbigint 0 bigint 2bigint self assertequalreprtake3 count10 2 5 repr10 12 5 15 0 c count3 5 self assertequalreprc count3 5 nextc self assertequalreprc count8 5 c count9 0 self assertequalreprc count9 0 nextc self assertequalreprc count9 0 c count9 3 self assertequalreprc count9 3 nextc self assertequalreprc count12 3 self assertequalreprc count12 3 self assertequalreprcount10 5 1 25 count10 5 1 25 self assertequalreprcount10 5 1 count10 5 suppress step1 when it s an int self assertequalreprcount10 5 1 00 count10 5 1 0 do show float values lilke 1 0 self assertequalreprcount10 1 00 count10 1 0 c count10 1 0 self assertequaltypenextc int self assertequaltypenextc float for i in sys maxsize5 sys maxsize5 10 1 0 10 sys maxsize5 sys maxsize5 for j in sys maxsize5 sys maxsize5 10 1 0 1 10 sys maxsize5 sys maxsize5 test repr r1 reprcounti j if j 1 r2 countr i else r2 countr r i j self assertequalr1 r2 for proto in rangepickle highestprotocol 1 self pickletestproto counti j def testcycleself self assertequaltake10 cycle abc list abcabcabca self assertequallistcycle self assertraisestypeerror cycle self assertraisestypeerror cycle 5 self assertequallistislicecyclegen3 10 0 1 2 0 1 2 0 1 2 0 pickledeprecated def testcyclecopypickleself check copy deepcopy pickle c cycle abc self assertequalnextc a simple copy currently not supported because reduce returns an internal iterator self assertequaltake10 copy copyc list bcabcabcab self assertequaltake10 copy deepcopyc list bcabcabcab for proto in rangepickle highestprotocol 1 self assertequaltake10 pickle loadspickle dumpsc proto list bcabcabcab nextc self assertequaltake10 pickle loadspickle dumpsc proto list cabcabcabc nextc nextc for proto in rangepickle highestprotocol 1 self pickletestproto cycle abc for proto in rangepickle highestprotocol 1 test with partial consumed input iterable it iter abcde c cycleit nextc for i in range2 consume 2 of 5 inputs p pickle dumpsc proto d pickle loadsp rebuild the cycle object self assertequaltake20 d list cdeabcdeabcdeabcdeab test with completely consumed input iterable it iter abcde c cycleit nextc for i in range7 consume 7 of 5 inputs p pickle dumpsc proto d pickle loadsp rebuild the cycle object self assertequaltake20 d list cdeabcdeabcdeabcdeab pickledeprecated def testcycleunpicklecompatself testcases b citertoolsncyclencbuiltinniternli1nai2nai3natri1nbtrli1nai0ntb b citertoolsncyclencbuiltinniternkx01kx02kx03etrkx01btrkx01akx00tb b x80x02citertoolsncyclencbuiltinniternkx01kx02kx03ex85rkx01bx85rkx01akx00x86b b x80x03citertoolsncyclencbuiltinsniternkx01kx02kx03ex85rkx01bx85rkx01akx00x86b b x80x04x95x00x00x00x00x00x00x00x8ctitertoolsx8cx05cyclex93x8cx08builtinsx8cx04iterx93kx01kx02kx03ex85rkx01bx85rkx01akx00x86b b citertoolsncyclencbuiltinniternlp0ni1nai2nai3natri1nbtrg0ni1ntb b citertoolsncyclencbuiltinniternqx00kx01kx02kx03etrkx01btrhx00kx01tb b x80x02citertoolsncyclencbuiltinniternqx00kx01kx02kx03ex85rkx01bx85rhx00kx01x86b b x80x03citertoolsncyclencbuiltinsniternqx00kx01kx02kx03ex85rkx01bx85rhx00kx01x86b b x80x04x95x00x00x00x00x00x00x00x8ctitertoolsx8cx05cyclex93x8cx08builtinsx8cx04iterx93x94kx01kx02kx03ex85rkx01bx85rhx00kx01x86b b citertoolsncyclencbuiltinniternli1nai2nai3natri1nbtrli1nai00ntb b citertoolsncyclencbuiltinniternkx01kx02kx03etrkx01btrkx01ai00ntb b x80x02citertoolsncyclencbuiltinniternkx01kx02kx03ex85rkx01bx85rkx01ax89x86b b x80x03citertoolsncyclencbuiltinsniternkx01kx02kx03ex85rkx01bx85rkx01ax89x86b b x80x04x95x00x00x00x00x00x00x00x8ctitertoolsx8cx05cyclex93x8cx08builtinsx8cx04iterx93kx01kx02kx03ex85rkx01bx85rkx01ax89x86b b citertoolsncyclencbuiltinniternlp0ni1nai2nai3natri1nbtrg0ni01ntb b citertoolsncyclencbuiltinniternqx00kx01kx02kx03etrkx01btrhx00i01ntb b x80x02citertoolsncyclencbuiltinniternqx00kx01kx02kx03ex85rkx01bx85rhx00x88x86b b x80x03citertoolsncyclencbuiltinsniternqx00kx01kx02kx03ex85rkx01bx85rhx00x88x86b b x80x04x95 x00x00x00x00x00x00x00x8ctitertoolsx8cx05cyclex93x8cx08builtinsx8cx04iterx93x94kx01kx02kx03ex85rkx01bx85rhx00x88x86b assert lentestcases 20 for t in testcases it pickle loadst self assertequaltake10 it 2 3 1 2 3 1 2 3 1 2 pickledeprecated def testcyclesetstateself verify both modes for restoring state mode 0 is efficient it uses an incompletely consumed input iterator to build a cycle object and then passes in state with a list of previously consumed values there is no data overlap between the two c cycle defg c setstatelist abc 0 self assertequaltake20 c list defgabcdefgabcdefgab mode 1 is inefficient it starts with a cycle object built from an iterator over the remaining elements in a partial cycle and then passes in state with all of the previously seen values this overlaps values included in the iterator c cycle defg c setstatelist abcdefg 1 self assertequaltake20 c list defgabcdefgabcdefgab the first argument to setstate needs to be a tuple with self assertraisestypeerror cycle defg setstatelist abcdefg 0 the first argument in the setstate tuple must be a list with self assertraisestypeerror c cycle defg c setstatetuple defg 0 take20 c the second argument in the setstate tuple must be an int with self assertraisestypeerror cycle defg setstatelist abcdefg x self assertraisestypeerror cycle setstate self assertraisestypeerror cycle setstate pickledeprecated def testgroupbyself check whether it accepts arguments correctly self assertequal listgroupby self assertequal listgroupby keyid self assertraisestypeerror list groupby abc self assertraisestypeerror groupby none self assertraisestypeerror groupby abc lambda x x 10 check normal input s 0 10 20 0 11 21 0 12 21 1 13 21 1 14 22 2 15 22 3 16 23 3 17 23 dup for k g in groupbys lambda r r0 for elem in g self assertequalk elem0 dup appendelem self assertequals dup check normal pickled for proto in rangepickle highestprotocol 1 dup for k g in pickle loadspickle dumpsgroupbys testr proto for elem in g self assertequalk elem0 dup appendelem self assertequals dup check nested case dup for k g in groupbys testr for ik ig in groupbyg testr2 for elem in ig self assertequalk elem0 self assertequalik elem2 dup appendelem self assertequals dup check nested and pickled for proto in rangepickle highestprotocol 1 dup for k g in pickle loadspickle dumpsgroupbys testr proto for ik ig in pickle loadspickle dumpsgroupbyg testr2 proto for elem in ig self assertequalk elem0 self assertequalik elem2 dup appendelem self assertequals dup check case where inner iterator is not used keys k for k g in groupbys testr expectedkeys setr0 for r in s self assertequalsetkeys expectedkeys self assertequallenkeys lenexpectedkeys check case where inner iterator is used after advancing the groupby iterator s listzip aabbbaaaa range9 it groupbys testr g1 nextit g2 nextit g3 nextit self assertequallistg1 self assertequallistg2 self assertequalnextg3 a 5 listit exhaust the groupby iterator self assertequallistg3 for proto in rangepickle highestprotocol 1 it groupbys testr g nextit nextit nextit self assertequallistpickle loadspickle dumpsg proto exercise pipes and filters style s abracadabra sort s uniq r k for k g in groupbysorteds self assertequalr a b c d r sort s uniq d r k for k g in groupbysorteds if listisliceg 1 2 self assertequalr a b r sort s uniq c r lenlistg k for k g in groupbysorteds self assertequalr 5 a 2 b 1 c 1 d 2 r sort s uniq c sort rn head 3 r sortedlenlistg k for k g in groupbysorteds reversetrue 3 self assertequalr 5 a 2 r 2 b iter next failure class expectederrorexception pass def delayedraisen0 for i in rangen yield yo raise expectederror def gulpiterable keypnone funclist return funcg for k g in groupbyiterable keyp iter next failure on outer object self assertraisesexpectederror gulp delayedraise0 iter next failure on inner object self assertraisesexpectederror gulp delayedraise1 eq failure class dummycmp def eqself dst raise expectederror s dummycmp dummycmp none eq failure on outer object self assertraisesexpectederror gulp s funcid eq failure on inner object self assertraisesexpectederror gulp s keyfunc failure def keyfuncobj if keyfunc skip 0 keyfunc skip 1 return obj else raise expectederror keyfunc failure on outer object keyfunc skip 0 self assertraisesexpectederror gulp none keyfunc keyfunc skip 1 self assertraisesexpectederror gulp none none keyfunc def testfilterself self assertequallistfilteriseven range6 0 2 4 self assertequallistfilternone 0 1 0 2 0 1 2 self assertequallistfilterbool 0 1 0 2 0 1 2 self assertequaltake4 filteriseven count 0 2 4 6 self assertraisestypeerror filter self assertraisestypeerror filter lambda x x self assertraisestypeerror filter lambda x x range6 7 self assertraisestypeerror filter iseven 3 self assertraisestypeerror next filterrange6 range6 check copy deepcopy pickle ans 0 2 4 c filteriseven range6 self assertequallistcopy copyc ans c filteriseven range6 self assertequallistcopy deepcopyc ans for proto in rangepickle highestprotocol 1 c filteriseven range6 self assertequallistpickle loadspickle dumpsc proto ans nextc self assertequallistpickle loadspickle dumpsc proto ans1 for proto in rangepickle highestprotocol 1 c filteriseven range6 self pickletestproto c pickledeprecated def testfilterfalseself self assertequallistfilterfalseiseven range6 1 3 5 self assertequallistfilterfalsenone 0 1 0 2 0 0 0 0 self assertequallistfilterfalsebool 0 1 0 2 0 0 0 0 self assertequaltake4 filterfalseiseven count 1 3 5 7 self assertraisestypeerror filterfalse self assertraisestypeerror filterfalse lambda x x self assertraisestypeerror filterfalse lambda x x range6 7 self assertraisestypeerror filterfalse iseven 3 self assertraisestypeerror next filterfalserange6 range6 for proto in rangepickle highestprotocol 1 self pickletestproto filterfalseiseven range6 def testzipself xxx this is rather silly now that builtin zip calls zip ans x y for x y in zip abc count self assertequalans a 0 b 1 c 2 self assertequallistzip abc range6 lzip abc range6 self assertequallistzip abcdef range3 lzip abcdef range3 self assertequaltake3 zip abcdef count lzip abcdef range3 self assertequallistzip abcdef lzip abcdef self assertequallistzip lzip self assertraisestypeerror zip 3 self assertraisestypeerror zip range3 3 self assertequaltuplelistpair for pair in zip abc def lzip abc def self assertequalpair for pair in zip abc def lzip abc def support impldetailtuple reuse is specific to cpython pickledeprecated def testziptuplereuseself ids listmapid zip abc def self assertequalminids maxids ids listmapid listzip abc def self assertequallendict fromkeysids lenids check copy deepcopy pickle ans x y for x y in copy copyzip abc count self assertequalans a 0 b 1 c 2 ans x y for x y in copy deepcopyzip abc count self assertequalans a 0 b 1 c 2 for proto in rangepickle highestprotocol 1 ans x y for x y in pickle loadspickle dumpszip abc count proto self assertequalans a 0 b 1 c 2 for proto in rangepickle highestprotocol 1 testintermediate zip abc count nexttestintermediate ans x y for x y in pickle loadspickle dumpstestintermediate proto self assertequalans b 1 c 2 for proto in rangepickle highestprotocol 1 self pickletestproto zip abc count def testziplongestself for args in abc range6 range6 abc range1000 range2000 2100 range3000 3050 range1000 range0 range3000 3050 range1200 range1500 range1000 range0 range3000 3050 range1200 range1500 range0 target tupleargi if i lenarg else none for arg in args for i in rangemaxmaplen args self assertequallistziplongestargs target self assertequallistziplongestargs target target tuplee is none and x or e for e in t for t in target replace none fills with x self assertequallistziplongestargs dictfillvalue x target self assertequaltake3 ziplongest abcdef count listzip abcdef range3 take 3 from infinite input self assertequallistziplongest listzip self assertequallistziplongest listzip self assertequallistziplongest abcdef listzip abcdef self assertequallistziplongest abc defg listziplist abc none defg empty keyword dict self assertraisestypeerror ziplongest 3 self assertraisestypeerror ziplongest range3 3 for stmt in ziplongest abc fv1 ziplongest abc fillvalue1 boguskeywordnone try evalstmt globals locals except typeerror pass else self fail did not raise type in stmt self assertequaltuplelistpair for pair in ziplongest abc def listzip abc def self assertequalpair for pair in ziplongest abc def listzip abc def support impldetailtuple reuse is specific to cpython def testziplongesttuplereuseself ids listmapid ziplongest abc def self assertequalminids maxids ids listmapid listziplongest abc def self assertequallendict fromkeysids lenids pickledeprecated def testziplongestpicklingself for proto in rangepickle highestprotocol 1 self pickletestproto ziplongestabc def self pickletestproto ziplongestabc defgh self pickletestproto ziplongestabc defgh fillvalue1 self pickletestproto ziplongest defgh def testziplongestbaditerableself exception typeerror class baditerable def iterself raise exception with self assertraisestypeerror as cm ziplongestbaditerable self assertiscm exception exception def testbug7244self class repeater this class is similar to itertools repeat def initself o t e self o o self t intt self e e def iterself its iterator is itself return self def nextself if self t 0 self t 1 return self o else raise self e formerly this code in would fail in debug mode with undetected error and stop iteration r1 repeater1 3 stopiteration r2 repeater2 4 stopiteration def runr1 r2 result for i j in ziplongestr1 r2 fillvalue0 with support capturedoutput stdout printi j result appendi j return result self assertequalrunr1 r2 1 2 1 2 1 2 0 2 formerly the runtimeerror would be lost and stopiteration would stop as expected r1 repeater1 3 runtimeerror r2 repeater2 4 stopiteration it ziplongestr1 r2 fillvalue0 self assertequalnextit 1 2 self assertequalnextit 1 2 self assertequalnextit 1 2 self assertraisesruntimeerror next it def testpairwiseself self assertequallistpairwise self assertequallistpairwise a self assertequallistpairwise ab a b self assertequallistpairwise abcde a b b c c d d e self assertequallistpairwiserange10000 listziprange10000 range1 10000 with self assertraisestypeerror pairwise too few arguments with self assertraisestypeerror pairwise abc 10 too many arguments with self assertraisestypeerror pairwiseiterable abc keyword arguments with self assertraisestypeerror pairwisenone noniterable argument def testproductself for args result in zero iterables ab a b one iterable range2 range3 0 0 0 1 0 2 1 0 1 1 1 2 two iterables range0 range2 range3 first iterable with zero length range2 range0 range3 middle iterable with zero length range2 range3 range0 last iterable with zero length self assertequallistproductargs result for r in range4 self assertequallistproductargsr listproductargs dictrepeatr self assertequallenlistproductrange76 76 self assertraisestypeerror product range6 none def product1args kwds pools listmaptuple args kwds get repeat 1 n lenpools if n 0 yield return if anylenpool 0 for pool in pools return indices 0 n yield tuplepooli for pool i in zippools indices while 1 for i in reversedrangen right to left if indicesi lenpoolsi 1 continue indicesi 1 for j in rangei1 n indicesj 0 yield tuplepooli for pool i in zippools indices break else return def product2args kwds pure python version used in docs pools listmaptuple args kwds get repeat 1 result for pool in pools result xy for x in result for y in pool for prod in result yield tupleprod argtypes abc range0 range4 dicta1 b2 c3 set abcdefg range11 tuplerange13 for i in range100 args random choiceargtypes for j in rangerandom randrange5 expectedlen prodmaplen args self assertequallenlistproductargs expectedlen self assertequallistproductargs listproduct1args self assertequallistproductargs listproduct2args args mapiter args self assertequallenlistproductargs expectedlen support bigaddrspacetest def testproductoverflowself with self assertraisesoverflowerror memoryerror product ab 25 repeat225 support impldetailtuple reuse is specific to cpython def testproducttuplereuseself self assertequallensetmapid product abc def 1 self assertnotequallensetmapid listproduct abc def 1 pickledeprecated def testproductpicklingself check copy deepcopy pickle for args result in zero iterables ab a b one iterable range2 range3 0 0 0 1 0 2 1 0 1 1 1 2 two iterables range0 range2 range3 first iterable with zero length range2 range0 range3 middle iterable with zero length range2 range3 range0 last iterable with zero length self assertequallistcopy copyproductargs result self assertequallistcopy deepcopyproductargs result for proto in rangepickle highestprotocol 1 self pickletestproto productargs pickledeprecated def testproductissue25021self test that indices are properly clamped to the length of the tuples p product1 2 3 p setstate0 0x1000 will access tuple element 1 if not clamped self assertequalnextp 2 3 test that empty tuple in the list will result in an immediate stopiteration p product1 2 3 p setstate0 0 0x1000 will access tuple element 1 if not clamped self assertraisesstopiteration next p pickledeprecated def testrepeatself self assertequallistrepeatobject a times3 a a a self assertequallziprange3 repeat a 0 a 1 a 2 a self assertequallistrepeat a 3 a a a self assertequaltake3 repeat a a a a self assertequallistrepeat a 0 self assertequallistrepeat a 3 self assertraisestypeerror repeat self assertraisestypeerror repeat none 3 4 self assertraisestypeerror repeat none a r repeat10j self assertequalreprr repeat10j r repeat10j 5 self assertequalreprr repeat10j 5 listr self assertequalreprr repeat10j 0 check copy deepcopy pickle c repeatobject a times10 self assertequalnextc a self assertequaltake2 copy copyc list a 2 self assertequaltake2 copy deepcopyc list a 2 for proto in rangepickle highestprotocol 1 self pickletestproto repeatobject a times10 def testrepeatwithnegativetimesself self assertequalreprrepeat a 1 repeat a 0 self assertequalreprrepeat a 2 repeat a 0 self assertequalreprrepeat a times1 repeat a 0 self assertequalreprrepeat a times2 repeat a 0 pickledeprecated def testmapself self assertequallistmapoperator pow range3 range1 7 01 12 23 self assertequallistmaptupleize abc range5 a 0 b 1 c 2 self assertequallistmaptupleize abc count a 0 b 1 c 2 self assertequaltake2 maptupleize abc count a 0 b 1 self assertequallistmapoperator pow self assertraisestypeerror map self assertraisestypeerror list mapnone range3 range3 self assertraisestypeerror map operator neg self assertraisestypeerror next map10 range5 self assertraisesvalueerror next maperrfunc 4 5 self assertraisestypeerror next maponearg 4 5 check copy deepcopy pickle ans a 0 b 1 c 2 c maptupleize abc count self assertequallistcopy copyc ans c maptupleize abc count self assertequallistcopy deepcopyc ans for proto in rangepickle highestprotocol 1 c maptupleize abc count self pickletestproto c pickledeprecated def teststarmapself self assertequalliststarmapoperator pow ziprange3 range1 7 01 12 23 self assertequaltake3 starmapoperator pow zipcount count1 01 12 23 self assertequalliststarmapoperator pow self assertequalliststarmapoperator pow iter4 5 45 self assertraisestypeerror list starmapoperator pow none self assertraisestypeerror starmap self assertraisestypeerror starmap operator pow 4 5 extra self assertraisestypeerror next starmap10 4 5 self assertraisesvalueerror next starmaperrfunc 4 5 self assertraisestypeerror next starmaponearg 4 5 check copy deepcopy pickle ans 01 12 23 c starmapoperator pow ziprange3 range1 7 self assertequallistcopy copyc ans c starmapoperator pow ziprange3 range1 7 self assertequallistcopy deepcopyc ans for proto in rangepickle highestprotocol 1 c starmapoperator pow ziprange3 range1 7 self pickletestproto c pickledeprecated def testisliceself for args in isliceargs should agree with rangeargs 10 20 3 10 3 20 10 20 10 10 10 3 20 self assertequallistislicerange100 args listrangeargs for args tgtargs in stop when seqn is exhausted 10 110 3 10 100 3 10 110 10 100 110 100 self assertequallistislicerange100 args listrangetgtargs test stopnone self assertequallistislicerange10 none listrange10 self assertequallistislicerange10 none none listrange10 self assertequallistislicerange10 none none none listrange10 self assertequallistislicerange10 2 none listrange2 10 self assertequallistislicerange10 1 none 2 listrange1 10 2 test number of items consumed sf 1171417 it iterrange10 self assertequallistisliceit 3 listrange3 self assertequallistit listrange3 10 it iterrange10 self assertequallistisliceit 3 3 self assertequallistit listrange3 10 test invalid arguments ra range10 self assertraisestypeerror islice ra self assertraisestypeerror islice ra 1 2 3 4 self assertraisesvalueerror islice ra 5 10 1 self assertraisesvalueerror islice ra 1 5 1 self assertraisesvalueerror islice ra 1 10 1 self assertraisesvalueerror islice ra 1 10 0 self assertraisesvalueerror islice ra a self assertraisesvalueerror islice ra a 1 self assertraisesvalueerror islice ra 1 a self assertraisesvalueerror islice ra a 1 1 self assertraisesvalueerror islice ra 1 a 1 self assertequallenlistislicecount 1 10 maxsize 1 issue 10323 less islice in a predictable state c count self assertequallistislicec 1 3 50 1 self assertequalnextc 3 check copy deepcopy pickle for args in isliceargs should agree with rangeargs 10 20 3 10 3 20 10 20 10 3 20 self assertequallistcopy copyislicerange100 args listrangeargs self assertequallistcopy deepcopyislicerange100 args listrangeargs for proto in rangepickle highestprotocol 1 self pickletestproto islicerange100 args issue 21321 check source iterator is not referenced from islice after the latter has been exhausted it x for x in 1 2 wr weakref refit it isliceit 1 self assertisnotnonewr listit exhaust the iterator support gccollect self assertisnonewr issue 30537 islice can accept integerlike objects as arguments class intlikeobject def initself val self val val def indexself return self val self assertequallistislicerange100 intlike10 listrange10 self assertequallistislicerange100 intlike10 intlike50 listrange10 50 self assertequallistislicerange100 intlike10 intlike50 intlike5 listrange10 50 5 pickledeprecated def testtakewhileself data 1 3 5 20 2 4 6 8 self assertequallisttakewhileunderten data 1 3 5 self assertequallisttakewhileunderten self assertraisestypeerror takewhile self assertraisestypeerror takewhile operator pow self assertraisestypeerror takewhile operator pow 4 5 extra self assertraisestypeerror next takewhile10 4 5 self assertraisesvalueerror next takewhileerrfunc 4 5 t takewhilebool 1 1 1 0 0 0 self assertequallistt 1 1 1 self assertraisesstopiteration next t check copy deepcopy pickle self assertequallistcopy copytakewhileunderten data 1 3 5 self assertequallistcopy deepcopytakewhileunderten data 1 3 5 for proto in rangepickle highestprotocol 1 self pickletestproto takewhileunderten data pickledeprecated def testdropwhileself data 1 3 5 20 2 4 6 8 self assertequallistdropwhileunderten data 20 2 4 6 8 self assertequallistdropwhileunderten self assertraisestypeerror dropwhile self assertraisestypeerror dropwhile operator pow self assertraisestypeerror dropwhile operator pow 4 5 extra self assertraisestypeerror next dropwhile10 4 5 self assertraisesvalueerror next dropwhileerrfunc 4 5 check copy deepcopy pickle self assertequallistcopy copydropwhileunderten data 20 2 4 6 8 self assertequallistcopy deepcopydropwhileunderten data 20 2 4 6 8 for proto in rangepickle highestprotocol 1 self pickletestproto dropwhileunderten data pickledeprecated def testteeself n 200 a b tee test empty iterator self assertequallista self assertequallistb a b teeirangen test 100 interleaved self assertequallzipa b lziprangen rangen a b teeirangen test 0 interleaved self assertequallista listrangen self assertequallistb listrangen a b teeirangen test dealloc of leading iterator for i in range100 self assertequalnexta i del a self assertequallistb listrangen a b teeirangen test dealloc of trailing iterator for i in range100 self assertequalnexta i del b self assertequallista listrange100 n for j in range5 test randomly interleaved order 0n 1n random shuffleorder lists its teeirangen for i in order value nextitsi listsi appendvalue self assertequallists0 listrangen self assertequallists1 listrangen test argument format checking self assertraisestypeerror tee self assertraisestypeerror tee 3 self assertraisestypeerror tee 1 2 x self assertraisestypeerror tee 1 2 3 x tee object should be instantiable a b tee abc c typea def self assertequallistc list def test longlagged and multiway split a b c teerange2000 3 for i in range100 self assertequalnexta i self assertequallistb listrange2000 self assertequalnextc nextc listrange2 self assertequallista listrange100 2000 self assertequallistc listrange2 2000 test values of n self assertraisestypeerror tee abc invalid self assertraisesvalueerror tee 1 for n in range5 result tee abc n self assertequaltyperesult tuple self assertequallenresult n self assertequallistx for x in result list abc n tee passthrough to copyable iterator a b tee abc c d teea self asserttruea is c test teenew t1 t2 tee abc tnew typet1 self assertraisestypeerror tnew self assertraisestypeerror tnew 10 t3 tnewt1 self asserttruelistt1 listt2 listt3 list abc test that tee objects are weak referencable a b teerange10 p weakref proxya self assertequalgetattrp class typeb del a support gccollect for pypy or other gcs self assertraisesreferenceerror getattr p class ans list abc longans listrange10000 check copy a b tee abc self assertequallistcopy copya ans self assertequallistcopy copyb ans a b teelistrange10000 self assertequallistcopy copya longans self assertequallistcopy copyb longans check partially consumed copy a b tee abc take2 a take1 b self assertequallistcopy copya ans2 self assertequallistcopy copyb ans1 self assertequallista ans2 self assertequallistb ans1 a b teerange10000 take100 a take60 b self assertequallistcopy copya longans100 self assertequallistcopy copyb longans60 self assertequallista longans100 self assertequallistb longans60 check deepcopy a b tee abc self assertequallistcopy deepcopya ans self assertequallistcopy deepcopyb ans self assertequallista ans self assertequallistb ans a b teerange10000 self assertequallistcopy deepcopya longans self assertequallistcopy deepcopyb longans self assertequallista longans self assertequallistb longans check partially consumed deepcopy a b tee abc take2 a take1 b self assertequallistcopy deepcopya ans2 self assertequallistcopy deepcopyb ans1 self assertequallista ans2 self assertequallistb ans1 a b teerange10000 take100 a take60 b self assertequallistcopy deepcopya longans100 self assertequallistcopy deepcopyb longans60 self assertequallista longans100 self assertequallistb longans60 check pickle for proto in rangepickle highestprotocol 1 self pickletestproto itertee abc a b tee abc self pickletestproto a compareans self pickletestproto b compareans issue 13454 crash when deleting backward iterator from tee def testteedelbackwardself forward backward teerepeatnone 20000000 try anyforward exhaust the iterator del backward except del forward backward raise def testteereenterself class i first true def iterself return self def nextself first self first self first false if first return nextb a b teei with self assertraisesregexruntimeerror tee nexta threadinghelper requiresworkingthreading def testteeconcurrentself start threading event finish threading event class i def iterself return self def nextself start set finish wait a b teei thread threading threadtargetnext argsa thread start try start wait with self assertraisesregexruntimeerror tee nextb finally finish set thread join def teststopiterationself self assertraisesstopiteration next zip for f in chain cycle zip groupby self assertraisesstopiteration next f self assertraisesstopiteration next fstopnow self assertraisesstopiteration next islice none self assertraisesstopiteration next islicestopnow none p q tee self assertraisesstopiteration next p self assertraisesstopiteration next q p q teestopnow self assertraisesstopiteration next p self assertraisesstopiteration next q self assertraisesstopiteration next repeatnone 0 for f in filter filterfalse map takewhile dropwhile starmap self assertraisesstopiteration next flambda x x self assertraisesstopiteration next flambda x x stopnow support cpythononly def testcombinationsresultgcself bpo42536 combinations s tuplereuse speed trick breaks the gc s assumptions about what can be untracked make sure we retrack result tuples whenever we reuse them it combinationsnone 1 nextit gc collect that gc collection probably untracked the recycled internal result tuple which has the value none make sure it s retracked when it s mutated and returned from next self asserttruegc istrackednextit support cpythononly def testcombinationswithreplacementresultgcself ditto for combinationswithreplacement it combinationswithreplacementnone 1 nextit gc collect self asserttruegc istrackednextit support cpythononly def testpermutationsresultgcself ditto for permutations it permutationsnone 1 nextit gc collect self asserttruegc istrackednextit support cpythononly def testproductresultgcself ditto for product it productnone nextit gc collect self asserttruegc istrackednextit support cpythononly def testziplongestresultgcself ditto for ziplongest it ziplongest gc collect self asserttruegc istrackednextit support cpythononly def testimmutabletypesself from itertools import grouper tee teedataobject dataset accumulate batched chain combinations combinationswithreplacement compress count cycle dropwhile filterfalse groupby grouper islice pairwise permutations product repeat starmap takewhile tee teedataobject ziplongest for tp in dataset with self subtesttptp with self assertraisesregextypeerror immutable tp foobar 1 class testexamplesunittest testcase def testaccumulateself self assertequallistaccumulate1 2 3 4 5 1 3 6 10 15 pickledeprecated def testaccumulatereducibleself check copy deepcopy pickle data 1 2 3 4 5 accumulated 1 3 6 10 15 for proto in rangepickle highestprotocol 1 it accumulatedata self assertequallistpickle loadspickle dumpsit proto accumulated self assertequalnextit 1 self assertequallistpickle loadspickle dumpsit proto accumulated1 it accumulatedata self assertequalnextit 1 self assertequallistcopy deepcopyit accumulated1 self assertequallistcopy copyit accumulated1 pickledeprecated def testaccumulatereduciblenoneself issue 25718 total is none it accumulatenone none none operator is self assertequalnextit none for proto in rangepickle highestprotocol 1 itcopy pickle loadspickle dumpsit proto self assertequallistitcopy true false self assertequallistcopy deepcopyit true false self assertequallistcopy copyit true false def testchainself self assertequal joinchain abc def abcdef def testchainfromiterableself self assertequal joinchain fromiterable abc def abcdef def testcombinationsself self assertequallistcombinations abcd 2 a b a c a d b c b d c d self assertequallistcombinationsrange4 3 0 1 2 0 1 3 0 2 3 1 2 3 def testcombinationswithreplacementself self assertequallistcombinationswithreplacement abc 2 a a a b a c b b b c c c def testcompressself self assertequallistcompress abcdef 1 0 1 0 1 1 list acef def testcountself self assertequallistislicecount10 5 10 11 12 13 14 def testcycleself self assertequallistislicecycle abcd 12 list abcdabcdabcd def testdropwhileself self assertequallistdropwhilelambda x x5 1 4 6 4 1 6 4 1 def testgroupbyself self assertequalk for k g in groupby aaaabbbccdaabbb list abcdab self assertequallistg for k g in groupby aaaabbbccd list aaaa list bbb list cc list d def testfilterself self assertequallistfilterlambda x x2 range10 1 3 5 7 9 def testfilterfalseself self assertequallistfilterfalselambda x x2 range10 0 2 4 6 8 def testmapself self assertequallistmappow 2 3 10 5 2 3 32 9 1000 def testisliceself self assertequallistislice abcdefg 2 list ab self assertequallistislice abcdefg 2 4 list cd self assertequallistislice abcdefg 2 none list cdefg self assertequallistislice abcdefg 0 none 2 list aceg def testzipself self assertequallistzip abcd xy a x b y def testziplongestself self assertequallistziplongest abcd xy fillvalue a x b y c d def testpermutationsself self assertequallistpermutations abcd 2 listmaptuple ab ac ad ba bc bd ca cb cd da db dc split self assertequallistpermutationsrange3 0 1 2 0 2 1 1 0 2 1 2 0 2 0 1 2 1 0 def testproductself self assertequallistproduct abcd xy listmaptuple ax ay bx by cx cy dx dy split self assertequallistproductrange2 repeat3 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 def testrepeatself self assertequallistrepeat10 3 10 10 10 def teststapmapself self assertequalliststarmappow 2 5 3 2 10 3 32 9 1000 def testtakewhileself self assertequallisttakewhilelambda x x5 1 4 6 4 1 1 4 class testpurepythonroughequivalentsunittest testcase def testbatchedrecipeself def batchedrecipeiterable n batch data into tuples of length n the last batch may be shorter batched abcdefg 3 abc def g if n 1 raise valueerror n must be at least one it iteriterable while batch tupleisliceit n yield batch for iterable n in product a ab abc abcd abcde abcdef abcdefg none 1 0 1 2 3 4 5 6 7 8 9 none with self subtestiterableiterable nn try e1 r1 none listbatchediterable n except exception as e e1 r1 typee none try e2 r2 none listbatchedrecipeiterable n except exception as e e2 r2 typee none self assertequalr1 r2 self assertequale1 e2 staticmethod def isliceiterable args s sliceargs start stop step s start or 0 s stop or sys maxsize s step or 1 it iterrangestart stop step try nexti nextit except stopiteration consume iterable up to the start position for i element in ziprangestart iterable pass return try for i element in enumerateiterable if i nexti yield element nexti nextit except stopiteration consume to stop for i element in ziprangei 1 stop iterable pass def testislicerecipeself self assertequallistself islice abcdefg 2 list ab self assertequallistself islice abcdefg 2 4 list cd self assertequallistself islice abcdefg 2 none list cdefg self assertequallistself islice abcdefg 0 none 2 list aceg test items consumed it iterrange10 self assertequallistself isliceit 3 listrange3 self assertequallistit listrange3 10 it iterrange10 self assertequallistself isliceit 3 3 self assertequallistit listrange3 10 test that slice finishes in predictable state c count self assertequallistself islicec 1 3 50 1 self assertequalnextc 3 class testgcunittest testcase def makecycleself iterator container container appenditerator nextiterator del container iterator def testaccumulateself a self makecycleaccumulate1 2 a 3 a def testbatchedself a self makecyclebatched1 2 a 3 2 a def testchainself a self makecyclechaina a def testchainfromiterableself a self makecyclechain fromiterablea a def testcombinationsself a self makecyclecombinations1 2 a 3 3 a def testcombinationswithreplacementself a self makecyclecombinationswithreplacement1 2 a 3 3 a def testcompressself a self makecyclecompress abcdef 1 0 1 0 1 0 a def testcountself a int type int int dictxa self makecyclecountint0 int1 a def testcycleself a self makecyclecyclea2 a def testdropwhileself a self makecycledropwhilebool 0 a a a def testgroupbyself a self makecyclegroupbya2 lambda x x a def testissue2246self issue 2246 the grouper iterator was not included in gc n 10 keyfunc lambda x x for i j in groupbyrangen keykeyfunc keyfunc dict setdefault x appendj def testfilterself a self makecyclefilterlambda x true a2 a def testfilterfalseself a self makecyclefilterfalselambda x false a a def testzipself a self makecyclezipa2 a3 a def testziplongestself a self makecycleziplongesta2 a3 a b a none self makecycleziplongesta2 a3 fillvalueb a def testmapself a self makecyclemaplambda x x a2 a def testisliceself a self makecycleislicea2 none a def testpairwiseself a self makecyclepairwisea5 a def testpermutationsself a self makecyclepermutations1 2 a 3 3 a def testproductself a self makecycleproduct1 2 a 3 repeat3 a def testrepeatself a self makecyclerepeata a def teststarmapself a self makecyclestarmaplambda t t a a2 a def testtakewhileself a self makecycletakewhilebool 1 0 a a a def rseqn regular generator for i in seqn yield i class g sequence using getitem def initself seqn self seqn seqn def getitemself i return self seqni class i sequence using iterator protocol def initself seqn self seqn seqn self i 0 def iterself return self def nextself if self i lenself seqn raise stopiteration v self seqnself i self i 1 return v class ig sequence using iterator protocol defined with a generator def initself seqn self seqn seqn self i 0 def iterself for val in self seqn yield val class x missing getitem and iter def initself seqn self seqn seqn self i 0 def nextself if self i lenself seqn raise stopiteration v self seqnself i self i 1 return v class n iterator missing next def initself seqn self seqn seqn self i 0 def iterself return self class e test propagation of exceptions def initself seqn self seqn seqn self i 0 def iterself return self def nextself 3 0 class e2 test propagation of exceptions after two iterations def initself seqn self seqn seqn self i 0 def iterself return self def nextself if self i 2 raise zerodivisionerror v self seqnself i self i 1 return v class s test immediate stop def initself seqn pass def iterself return self def nextself raise stopiteration def lseqn test multiple tiers of iterators return chainmaplambda x x riggseqn class testvariousiteratorargsunittest testcase def testaccumulateself s 1 2 3 4 5 r 1 3 6 10 15 n lens for g in g i ig l r self assertequallistaccumulategs r self assertequallistaccumulatess self assertraisestypeerror accumulate xs self assertraisestypeerror accumulate ns self assertraiseszerodivisionerror list accumulatees def testbatchedself s abcde r a b c d e n 2 for g in g i ig l r with self subtestgg self assertequallistbatchedgs n r self assertequallistbatchedss 2 self assertraisestypeerror batched xs 2 self assertraisestypeerror batched ns 2 self assertraiseszerodivisionerror list batchedes 2 self assertraiseszerodivisionerror list batchede2s 4 def testchainself for s in 123 range1000 do 1 2 range2000 2200 5 for g in g i ig s l r self assertequallistchaings listgs self assertequallistchaings gs listgslistgs self assertraisestypeerror list chainxs self assertraisestypeerror list chainns self assertraiseszerodivisionerror list chaines def testcompressself for s in 123 range1000 do 1 2 range2000 2200 5 n lens for g in g i ig s l r self assertequallistcompressgs repeat1 listgs self assertraisestypeerror compress xs repeat1 self assertraisestypeerror compress ns repeat1 self assertraiseszerodivisionerror list compresses repeat1 def testproductself for s in 123 range1000 do 1 2 range2000 2200 5 self assertraisestypeerror product xs self assertraisestypeerror product ns self assertraiseszerodivisionerror product es def testcycleself for s in 123 range1000 do 1 2 range2000 2200 5 for g in g i ig s l r tgtlen lens 3 expected listgs3 actual listislicecyclegs tgtlen self assertequalactual expected self assertraisestypeerror cycle xs self assertraisestypeerror cycle ns self assertraiseszerodivisionerror list cyclees def testgroupbyself for s in range10 range0 range1000 7 11 range2000 2200 5 for g in g i ig s l r self assertequalk for k sb in groupbygs listgs self assertraisestypeerror groupby xs self assertraisestypeerror groupby ns self assertraiseszerodivisionerror list groupbyes def testfilterself for s in range10 range0 range1000 7 11 range2000 2200 5 for g in g i ig s l r self assertequallistfilteriseven gs x for x in gs if isevenx self assertraisestypeerror filter iseven xs self assertraisestypeerror filter iseven ns self assertraiseszerodivisionerror list filteriseven es def testfilterfalseself for s in range10 range0 range1000 7 11 range2000 2200 5 for g in g i ig s l r self assertequallistfilterfalseiseven gs x for x in gs if isoddx self assertraisestypeerror filterfalse iseven xs self assertraisestypeerror filterfalse iseven ns self assertraiseszerodivisionerror list filterfalseiseven es def testzipself for s in 123 range1000 do 1 2 range2000 2200 5 for g in g i ig s l r self assertequallistzipgs lzipgs self assertequallistzipgs gs lzipgs gs self assertraisestypeerror zip xs self assertraisestypeerror zip ns self assertraiseszerodivisionerror list zipes def testziplongestself for s in 123 range1000 do 1 2 range2000 2200 5 for g in g i ig s l r self assertequallistziplongestgs listzipgs self assertequallistziplongestgs gs listzipgs gs self assertraisestypeerror ziplongest xs self assertraisestypeerror ziplongest ns self assertraiseszerodivisionerror list ziplongestes def testmapself for s in range10 range0 range100 7 11 range20 50 5 for g in g i ig s l r self assertequallistmaponearg gs oneargx for x in gs self assertequallistmapoperator pow gs gs xx for x in gs self assertraisestypeerror map onearg xs self assertraisestypeerror map onearg ns self assertraiseszerodivisionerror list maponearg es def testisliceself for s in 12345 range1000 do 1 2 range2000 2200 5 for g in g i ig s l r self assertequallistislicegs 1 none 2 listgs1 2 self assertraisestypeerror islice xs 10 self assertraisestypeerror islice ns 10 self assertraiseszerodivisionerror list islicees 10 def testpairwiseself for s in 123 range1000 do 1 2 range2000 2200 5 for g in g i ig s l r seq listgs expected listzipseq seq1 actual listpairwisegs self assertequalactual expected self assertraisestypeerror pairwise xs self assertraisestypeerror pairwise ns self assertraiseszerodivisionerror list pairwisees def teststarmapself for s in range10 range0 range100 7 11 range20 50 5 for g in g i ig s l r ss lzips s self assertequalliststarmapoperator pow gss xx for x in gs self assertraisestypeerror starmap operator pow xss self assertraisestypeerror starmap operator pow nss self assertraiseszerodivisionerror list starmapoperator pow ess def testtakewhileself for s in range10 range0 range1000 7 11 range2000 2200 5 for g in g i ig s l r tgt for elem in gs if not isevenelem break tgt appendelem self assertequallisttakewhileiseven gs tgt self assertraisestypeerror takewhile iseven xs self assertraisestypeerror takewhile iseven ns self assertraiseszerodivisionerror list takewhileiseven es def testdropwhileself for s in range10 range0 range1000 7 11 range2000 2200 5 for g in g i ig s l r tgt for elem in gs if not tgt and isoddelem continue tgt appendelem self assertequallistdropwhileisodd gs tgt self assertraisestypeerror dropwhile isodd xs self assertraisestypeerror dropwhile isodd ns self assertraiseszerodivisionerror list dropwhileisodd es def testteeself for s in 123 range1000 do 1 2 range2000 2200 5 for g in g i ig s l r it1 it2 teegs self assertequallistit1 listgs self assertequallistit2 listgs self assertraisestypeerror tee xs self assertraisestypeerror tee ns self assertraiseszerodivisionerror list teees0 class lengthtransparencyunittest testcase def testrepeatself self assertequaloperator lengthhintrepeatnone 50 50 self assertequaloperator lengthhintrepeatnone 0 0 self assertequaloperator lengthhintrepeatnone 12 12 def testrepeatwithnegativetimesself self assertequaloperator lengthhintrepeatnone 1 0 self assertequaloperator lengthhintrepeatnone 2 0 self assertequaloperator lengthhintrepeatnone times1 0 self assertequaloperator lengthhintrepeatnone times2 0 class regressiontestsunittest testcase def testsf793826self fix armin rigo s successful efforts to wreak havoc def mutatingtupletuple1 f tuple2 this builds a tuple t which is a copy of tuple1 then calls ft then mutates t to be equal to tuple2 needs lentuple1 lentuple2 def gvalue first1 if first del first fnextz return value items listtuple2 items1 1 listtuple1 gen mapg items z zipgenlentuple1 nextz def ft global t t t first listt first mutatingtuple1 2 3 f 4 5 6 second listt self assertequalfirst second def testsf950057self make sure that chain and cycle catch exceptions immediately rather than when shifting between input sources def gen1 hist append0 yield 1 hist append1 raise assertionerror hist append2 def gen2x hist append3 yield 2 hist append4 hist self assertraisesassertionerror list chaingen1 gen2false self assertequalhist 0 1 hist self assertraisesassertionerror list chaingen1 gen2true self assertequalhist 0 1 hist self assertraisesassertionerror list cyclegen1 self assertequalhist 0 1 support skipifpgotask support requiresresource cpu def testlongchainofemptyiterablesself make sure itertools chain doesn t run into recursion limits when dealing with long chains of empty iterables even with a high number this would probably only fail in pydebug mode it chain fromiterable for unused in range10000000 with self assertraisesstopiteration nextit def testissue303471self def fn if n 5 listb return n 6 for k b in groupbyrange10 f listb shouldn t crash def testissue303472self class k def initself v pass def eqself other nonlocal i i 1 if i 1 nextg none return true i 0 g nextgroupbyrange10 k1 for j in range2 nextg none shouldn t crash class subclasswithkwargstestunittest testcase def testkeywordsinsubclassself count is not subclassable testcases repeat 1 2 1 1 zip 1 2 ab 1 a 2 b filter none 0 1 1 filterfalse none 0 1 0 chain 1 2 3 4 1 2 3 map str 1 2 1 2 starmap operator pow 2 3 3 2 8 9 islice 1 2 3 4 1 3 2 3 takewhile iseven 2 3 4 2 dropwhile iseven 2 3 4 3 4 cycle 1 2 1 2 1 compress abc 1 0 1 a c for cls args result in testcases with self subtestcls class subclasscls pass u subclassargs self assertistypeu subclass self assertequallistisliceu 0 3 result with self assertraisestypeerror subclassargs newarg3 for cls args result in testcases constructors of repeat zip compress accept keyword arguments their subclasses need overriding new to support new keyword arguments if cls in repeat zip compress continue with self subtestcls class subclasswithinitcls def initself args newargnone self newarg newarg u subclasswithinitargs newarg3 self assertistypeu subclasswithinit self assertequallistisliceu 0 3 result self assertequalu newarg 3 for cls args result in testcases with self subtestcls class subclasswithnewcls def newcls args newargnone self super newcls args self newarg newarg return self u subclasswithnewargs newarg3 self assertistypeu subclasswithnew self assertequallistisliceu 0 3 result self assertequalu newarg 3 support cpythononly class sizeoftestunittest testcase def setupself self ssizet struct calcsize n checksizeof support checksizeof def testproductsizeofself basesize support calcobjsize 3pi check self checksizeof checkproduct ab 12 basesize 2 self ssizet checkproduct abc 10 basesize 10 self ssizet def testcombinationssizeofself basesize support calcobjsize 3pni check self checksizeof checkcombinations abcd 3 basesize 3 self ssizet checkcombinationsrange10 4 basesize 4 self ssizet def testcombinationswithreplacementsizeofself cwr combinationswithreplacement basesize support calcobjsize 3pni check self checksizeof checkcwr abcd 3 basesize 3 self ssizet checkcwrrange10 4 basesize 4 self ssizet def testpermutationssizeofself basesize support calcobjsize 4pni check self checksizeof checkpermutations abcd basesize 4 self ssizet 4 self ssizet checkpermutations abcd 3 basesize 4 self ssizet 3 self ssizet checkpermutations abcde 3 basesize 5 self ssizet 3 self ssizet checkpermutationsrange10 4 basesize 10 self ssizet 4 self ssizet def loadtestsloader tests pattern tests addtestdoctest doctestsuite return tests if name main unittest main run the test three times first verify that a deprecation warning is raised second run normally but with deprecationwarnings temporarily disabled third run with warnings promoted to errors root level methods for pickling ability test that an iterator is the same after pickling also when part consumed recursively expand iterables within sensible bounds can t expand it test the initial copy against the original take from the copy and create another copy and compare them in case there is less data than take one positional arg kw arg multiple types works with non numeric empty iterable iterable of length one too many args too few args unexpected kwd arg args that don t add unary operation test pickling too few arguments too many arguments non iterable input n is a string n is zero n is negative order is preserved and no data is lost each batch is an exact tuple all but the last batch is of size n missing r argument too many arguments pool is not iterable r is negative r n right number of combs no repeats lexicographic order r length combinations no duplicate elements keep original ordering elements taken from input iterable comb is a subsequence of the input iterable matches first pure python version matches second pure python version matches second pure python version test pickling test implementation detail tuple re use missing r argument too many arguments pool is not iterable r is negative number items returned n r 1 r n 1 when n 0 right number of combs no repeats lexicographic order compare to combs without replacement cases that should be identical rest should be supersets of regular combs r length combinations combo without consecutive repeats no repeats other than consecutive keep original ordering elements taken from input iterable comb is a subsequence of the input iterable matches first pure python version matches second pure python version test pickling test implementation detail tuple re use too few arguments too many arguments pool is not iterable r is negative r n r is not an int or none right number of perms no repeats lexicographic order r length permutations no duplicate elements elements taken from input iterable matches first pure python version matches second pure python version test r as none test default r test pickling test relationships between product permutations combinations and combinations_with_replacement check size check lexicographic order without repeated tuples check interrelationships cwr prods which are sorted perm prods with no dups comb perms that are sorted comb cwrs without dups comb perm that is a cwr comb cwr that is a perm comb both a cwr and a perm 1st arg not iterable 2nd arg not iterable too few args too many args check copy deepcopy pickle test repr check copy deepcopy pickle check proper internal error handling for large step sizes suppress step 1 when it s an int do show float values lilke 1 0 test repr check copy deepcopy pickle simple copy currently not supported because __reduce__ returns an internal iterator self assertequal take 10 copy copy c list bcabcabcab test with partial consumed input iterable consume 2 of 5 inputs rebuild the cycle object test with completely consumed input iterable consume 7 of 5 inputs rebuild the cycle object verify both modes for restoring state mode 0 is efficient it uses an incompletely consumed input iterator to build a cycle object and then passes in state with a list of previously consumed values there is no data overlap between the two mode 1 is inefficient it starts with a cycle object built from an iterator over the remaining elements in a partial cycle and then passes in state with all of the previously seen values this overlaps values included in the iterator the first argument to setstate needs to be a tuple the first argument in the setstate tuple must be a list the second argument in the setstate tuple must be an int check whether it accepts arguments correctly check normal input check normal pickled check nested case check nested and pickled check case where inner iterator is not used check case where inner iterator is used after advancing the groupby iterator exhaust the groupby iterator exercise pipes and filters style sort s uniq sort s uniq d sort s uniq c sort s uniq c sort rn head 3 iter __next__ failure iter __next__ failure on outer object iter __next__ failure on inner object __eq__ failure __eq__ failure on outer object __eq__ failure on inner object keyfunc failure keyfunc failure on outer object check copy deepcopy pickle xxx this is rather silly now that builtin zip calls zip check copy deepcopy pickle replace none fills with x take 3 from infinite input empty keyword dict this class is similar to itertools repeat its iterator is itself formerly this code in would fail in debug mode with undetected error and stop iteration formerly the runtimeerror would be lost and stopiteration would stop as expected too few arguments too many arguments keyword arguments non iterable argument zero iterables one iterable two iterables first iterable with zero length middle iterable with zero length last iterable with zero length right to left check copy deepcopy pickle zero iterables one iterable two iterables first iterable with zero length middle iterable with zero length last iterable with zero length test that indices are properly clamped to the length of the tuples will access tuple element 1 if not clamped test that empty tuple in the list will result in an immediate stopiteration will access tuple element 1 if not clamped check copy deepcopy pickle check copy deepcopy pickle check copy deepcopy pickle islice args should agree with range args stop when seqn is exhausted test stop none test number of items consumed sf 1171417 test invalid arguments issue 10323 less islice in a predictable state check copy deepcopy pickle islice args should agree with range args issue 21321 check source iterator is not referenced from islice after the latter has been exhausted exhaust the iterator issue 30537 islice can accept integer like objects as arguments check copy deepcopy pickle check copy deepcopy pickle test empty iterator test 100 interleaved test 0 interleaved test dealloc of leading iterator test dealloc of trailing iterator test randomly interleaved test argument format checking tee object should be instantiable test long lagged and multi way split test values of n tee pass through to copyable iterator test tee_new test that tee objects are weak referencable for pypy or other gcs check copy check partially consumed copy check deepcopy check partially consumed deepcopy check pickle issue 13454 crash when deleting backward iterator from tee exhaust the iterator bpo 42536 combinations s tuple reuse speed trick breaks the gc s assumptions about what can be untracked make sure we re track result tuples whenever we reuse them that gc collection probably untracked the recycled internal result tuple which has the value none make sure it s re tracked when it s mutated and returned from __next__ ditto for combinations_with_replacement ditto for permutations ditto for product ditto for zip_longest check copy deepcopy pickle issue 25718 total is none batched abcdefg 3 abc def g consume iterable up to the start position consume to stop test items consumed test that slice finishes in predictable state issue 2246 the _grouper iterator was not included in gc fix armin rigo s successful efforts to wreak havoc this builds a tuple t which is a copy of tuple1 then calls f t then mutates t to be equal to tuple2 needs len tuple1 len tuple2 make sure that chain and cycle catch exceptions immediately rather than when shifting between input sources make sure itertools chain doesn t run into recursion limits when dealing with long chains of empty iterables even with a high number this would probably only fail in py_debug mode shouldn t crash shouldn t crash count is not subclassable constructors of repeat zip compress accept keyword arguments their subclasses need overriding __new__ to support new keyword arguments
import doctest
import unittest
from test import support
from test.support import threading_helper
from itertools import *
import weakref
from decimal import Decimal
from fractions import Fraction
import operator
import random
import copy
import pickle
from functools import reduce
import sys
import struct
import threading
import gc
import warnings

def pickle_deprecated(testfunc):
    
    def inner(self):
        with self.assertWarns(DeprecationWarning):
            testfunc(self)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=DeprecationWarning)
            testfunc(self)
        with warnings.catch_warnings():
            warnings.simplefilter("error", category=DeprecationWarning)
            with self.assertRaises((DeprecationWarning, AssertionError, SystemError)):
                testfunc(self)

    return inner

maxsize = support.MAX_Py_ssize_t
minsize = -maxsize-1

def lzip(*args):
    return list(zip(*args))

def onearg(x):
    'Test function of one argument'
    return 2*x

def errfunc(*args):
    'Test function that raises an error'
    raise ValueError

def gen3():
    'Non-restartable source sequence'
    for i in (0, 1, 2):
        yield i

def isEven(x):
    'Test predicate'
    return x%2==0

def isOdd(x):
    'Test predicate'
    return x%2==1

def tupleize(*args):
    return args

def irange(n):
    for i in range(n):
        yield i

class StopNow:
    'Class emulating an empty iterable.'
    def __iter__(self):
        return self
    def __next__(self):
        raise StopIteration

def take(n, seq):
    'Convenience function for partially consuming a long of infinite iterable'
    return list(islice(seq, n))

def prod(iterable):
    return reduce(operator.mul, iterable, 1)

def fact(n):
    'Factorial'
    return prod(range(1, n+1))


def testR(r):
    return r[0]

def testR2(r):
    return r[2]

def underten(x):
    return x<10

picklecopiers = [lambda s, proto=proto: pickle.loads(pickle.dumps(s, proto))
                 for proto in range(pickle.HIGHEST_PROTOCOL + 1)]

class TestBasicOps(unittest.TestCase):

    def pickletest(self, protocol, it, stop=4, take=1, compare=None):
        
        def expand(it, i=0):
            
            if i > 10:
                raise RuntimeError("infinite recursion encountered")
            if isinstance(it, str):
                return it
            try:
                l = list(islice(it, stop))
            except TypeError:
                return it 
            return [expand(e, i+1) for e in l]

        
        dump = pickle.dumps(it, protocol)
        i2 = pickle.loads(dump)
        self.assertEqual(type(it), type(i2))
        a, b = expand(it), expand(i2)
        self.assertEqual(a, b)
        if compare:
            c = expand(compare)
            self.assertEqual(a, c)

        
        i3 = pickle.loads(dump)
        took = 0
        try:
            for i in range(take):
                next(i3)
                took += 1
        except StopIteration:
            pass 
        dump = pickle.dumps(i3, protocol)
        i4 = pickle.loads(dump)
        a, b = expand(i3), expand(i4)
        self.assertEqual(a, b)
        if compare:
            c = expand(compare[took:])
            self.assertEqual(a, c);

    @pickle_deprecated
    def test_accumulate(self):
        self.assertEqual(list(accumulate(range(10))),               
                          [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
        self.assertEqual(list(accumulate(iterable=range(10))),      
                          [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
        for typ in int, complex, Decimal, Fraction:                 
            self.assertEqual(
                list(accumulate(map(typ, range(10)))),
                list(map(typ, [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])))
        self.assertEqual(list(accumulate('abc')), ['a', 'ab', 'abc'])   
        self.assertEqual(list(accumulate([])), [])                  
        self.assertEqual(list(accumulate([7])), [7])                
        self.assertRaises(TypeError, accumulate, range(10), 5, 6)   
        self.assertRaises(TypeError, accumulate)                    
        self.assertRaises(TypeError, accumulate, x=range(10))       
        self.assertRaises(TypeError, list, accumulate([1, []]))     

        s = [2, 8, 9, 5, 7, 0, 3, 4, 1, 6]
        self.assertEqual(list(accumulate(s, min)),
                         [2, 2, 2, 2, 2, 0, 0, 0, 0, 0])
        self.assertEqual(list(accumulate(s, max)),
                         [2, 8, 9, 9, 9, 9, 9, 9, 9, 9])
        self.assertEqual(list(accumulate(s, operator.mul)),
                         [2, 16, 144, 720, 5040, 0, 0, 0, 0, 0])
        with self.assertRaises(TypeError):
            list(accumulate(s, chr))                                
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            self.pickletest(proto, accumulate(range(10)))           
            self.pickletest(proto, accumulate(range(10), initial=7))
        self.assertEqual(list(accumulate([10, 5, 1], initial=None)), [10, 15, 16])
        self.assertEqual(list(accumulate([10, 5, 1], initial=100)), [100, 110, 115, 116])
        self.assertEqual(list(accumulate([], initial=100)), [100])
        with self.assertRaises(TypeError):
            list(accumulate([10, 20], 100))

    def test_batched(self):
        self.assertEqual(list(batched('ABCDEFG', 3)),
                             [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)])
        self.assertEqual(list(batched('ABCDEFG', 2)),
                             [('A', 'B'), ('C', 'D'), ('E', 'F'), ('G',)])
        self.assertEqual(list(batched('ABCDEFG', 1)),
                            [('A',), ('B',), ('C',), ('D',), ('E',), ('F',), ('G',)])

        with self.assertRaises(TypeError):          
            list(batched('ABCDEFG'))
        with self.assertRaises(TypeError):
            list(batched('ABCDEFG', 3, None))       
        with self.assertRaises(TypeError):
            list(batched(None, 3))                  
        with self.assertRaises(TypeError):
            list(batched('ABCDEFG', 'hello'))       
        with self.assertRaises(ValueError):
            list(batched('ABCDEFG', 0))             
        with self.assertRaises(ValueError):
            list(batched('ABCDEFG', -1))            

        data = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        for n in range(1, 6):
            for i in range(len(data)):
                s = data[:i]
                batches = list(batched(s, n))
                with self.subTest(s=s, n=n, batches=batches):
                    
                    self.assertEqual(''.join(chain(*batches)), s)
                    
                    self.assertTrue(all(type(batch) is tuple for batch in batches))
                    
                    if batches:
                        last_batch = batches.pop()
                        self.assertTrue(all(len(batch) == n for batch in batches))
                        self.assertTrue(len(last_batch) <= n)
                        batches.append(last_batch)

    def test_chain(self):

        def chain2(*iterables):
            'Pure python version in the docs'
            for it in iterables:
                for element in it:
                    yield element

        for c in (chain, chain2):
            self.assertEqual(list(c('abc', 'def')), list('abcdef'))
            self.assertEqual(list(c('abc')), list('abc'))
            self.assertEqual(list(c('')), [])
            self.assertEqual(take(4, c('abc', 'def')), list('abcd'))
            self.assertRaises(TypeError, list,c(2, 3))

    def test_chain_from_iterable(self):
        self.assertEqual(list(chain.from_iterable(['abc', 'def'])), list('abcdef'))
        self.assertEqual(list(chain.from_iterable(['abc'])), list('abc'))
        self.assertEqual(list(chain.from_iterable([''])), [])
        self.assertEqual(take(4, chain.from_iterable(['abc', 'def'])), list('abcd'))
        self.assertRaises(TypeError, list, chain.from_iterable([2, 3]))
        self.assertEqual(list(islice(chain.from_iterable(repeat(range(5))), 2)), [0, 1])

    @pickle_deprecated
    def test_chain_reducible(self):
        for oper in [copy.deepcopy] + picklecopiers:
            it = chain('abc', 'def')
            self.assertEqual(list(oper(it)), list('abcdef'))
            self.assertEqual(next(it), 'a')
            self.assertEqual(list(oper(it)), list('bcdef'))

            self.assertEqual(list(oper(chain(''))), [])
            self.assertEqual(take(4, oper(chain('abc', 'def'))), list('abcd'))
            self.assertRaises(TypeError, list, oper(chain(2, 3)))
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            self.pickletest(proto, chain('abc', 'def'), compare=list('abcdef'))

    @pickle_deprecated
    def test_chain_setstate(self):
        self.assertRaises(TypeError, chain().__setstate__, ())
        self.assertRaises(TypeError, chain().__setstate__, [])
        self.assertRaises(TypeError, chain().__setstate__, 0)
        self.assertRaises(TypeError, chain().__setstate__, ([],))
        self.assertRaises(TypeError, chain().__setstate__, (iter([]), []))
        it = chain()
        it.__setstate__((iter(['abc', 'def']),))
        self.assertEqual(list(it), ['a', 'b', 'c', 'd', 'e', 'f'])
        it = chain()
        it.__setstate__((iter(['abc', 'def']), iter(['ghi'])))
        self.assertEqual(list(it), ['ghi', 'a', 'b', 'c', 'd', 'e', 'f'])

    @pickle_deprecated
    def test_combinations(self):
        self.assertRaises(TypeError, combinations, 'abc')       
        self.assertRaises(TypeError, combinations, 'abc', 2, 1) 
        self.assertRaises(TypeError, combinations, None)        
        self.assertRaises(ValueError, combinations, 'abc', -2)  

        for op in [lambda a:a] + picklecopiers:
            self.assertEqual(list(op(combinations('abc', 32))), [])     

            self.assertEqual(list(op(combinations('ABCD', 2))),
                             [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
            testIntermediate = combinations('ABCD', 2)
            next(testIntermediate)
            self.assertEqual(list(op(testIntermediate)),
                             [('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])

            self.assertEqual(list(op(combinations(range(4), 3))),
                             [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
            testIntermediate = combinations(range(4), 3)
            next(testIntermediate)
            self.assertEqual(list(op(testIntermediate)),
                             [(0,1,3), (0,2,3), (1,2,3)])

        def combinations1(iterable, r):
            'Pure python version shown in the docs'
            pool = tuple(iterable)
            n = len(pool)
            if r > n:
                return
            indices = list(range(r))
            yield tuple(pool[i] for i in indices)
            while 1:
                for i in reversed(range(r)):
                    if indices[i] != i + n - r:
                        break
                else:
                    return
                indices[i] += 1
                for j in range(i+1, r):
                    indices[j] = indices[j-1] + 1
                yield tuple(pool[i] for i in indices)

        def combinations2(iterable, r):
            'Pure python version shown in the docs'
            pool = tuple(iterable)
            n = len(pool)
            for indices in permutations(range(n), r):
                if sorted(indices) == list(indices):
                    yield tuple(pool[i] for i in indices)

        def combinations3(iterable, r):
            'Pure python version from cwr()'
            pool = tuple(iterable)
            n = len(pool)
            for indices in combinations_with_replacement(range(n), r):
                if len(set(indices)) == r:
                    yield tuple(pool[i] for i in indices)

        for n in range(7):
            values = [5*x-12 for x in range(n)]
            for r in range(n+2):
                result = list(combinations(values, r))
                self.assertEqual(len(result), 0 if r>n else fact(n) / fact(r) / fact(n-r)) 
                self.assertEqual(len(result), len(set(result)))         
                self.assertEqual(result, sorted(result))                
                for c in result:
                    self.assertEqual(len(c), r)                         
                    self.assertEqual(len(set(c)), r)                    
                    self.assertEqual(list(c), sorted(c))                
                    self.assertTrue(all(e in values for e in c))           
                    self.assertEqual(list(c),
                                     [e for e in values if e in c])      
                self.assertEqual(result, list(combinations1(values, r))) 
                self.assertEqual(result, list(combinations2(values, r))) 
                self.assertEqual(result, list(combinations3(values, r))) 

                for proto in range(pickle.HIGHEST_PROTOCOL + 1):
                    self.pickletest(proto, combinations(values, r))      

    @support.bigaddrspacetest
    def test_combinations_overflow(self):
        with self.assertRaises((OverflowError, MemoryError)):
            combinations("AA", 2**29)

        
    @support.impl_detail("tuple reuse is specific to CPython")
    def test_combinations_tuple_reuse(self):
        self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1)
        self.assertNotEqual(len(set(map(id, list(combinations('abcde', 3))))), 1)

    @pickle_deprecated
    def test_combinations_with_replacement(self):
        cwr = combinations_with_replacement
        self.assertRaises(TypeError, cwr, 'abc')       
        self.assertRaises(TypeError, cwr, 'abc', 2, 1) 
        self.assertRaises(TypeError, cwr, None)        
        self.assertRaises(ValueError, cwr, 'abc', -2)  

        for op in [lambda a:a] + picklecopiers:
            self.assertEqual(list(op(cwr('ABC', 2))),
                             [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
            testIntermediate = cwr('ABC', 2)
            next(testIntermediate)
            self.assertEqual(list(op(testIntermediate)),
                             [('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])


        def cwr1(iterable, r):
            'Pure python version shown in the docs'
            
            pool = tuple(iterable)
            n = len(pool)
            if not n and r:
                return
            indices = [0] * r
            yield tuple(pool[i] for i in indices)
            while 1:
                for i in reversed(range(r)):
                    if indices[i] != n - 1:
                        break
                else:
                    return
                indices[i:] = [indices[i] + 1] * (r - i)
                yield tuple(pool[i] for i in indices)

        def cwr2(iterable, r):
            'Pure python version shown in the docs'
            pool = tuple(iterable)
            n = len(pool)
            for indices in product(range(n), repeat=r):
                if sorted(indices) == list(indices):
                    yield tuple(pool[i] for i in indices)

        def numcombs(n, r):
            if not n:
                return 0 if r else 1
            return fact(n+r-1) / fact(r)/ fact(n-1)

        for n in range(7):
            values = [5*x-12 for x in range(n)]
            for r in range(n+2):
                result = list(cwr(values, r))

                self.assertEqual(len(result), numcombs(n, r))           
                self.assertEqual(len(result), len(set(result)))         
                self.assertEqual(result, sorted(result))                

                regular_combs = list(combinations(values, r))           
                if n == 0 or r <= 1:
                    self.assertEqual(result, regular_combs)            
                else:
                    self.assertTrue(set(result) >= set(regular_combs))     

                for c in result:
                    self.assertEqual(len(c), r)                         
                    noruns = [k for k,v in groupby(c)]                  
                    self.assertEqual(len(noruns), len(set(noruns)))     
                    self.assertEqual(list(c), sorted(c))                
                    self.assertTrue(all(e in values for e in c))           
                    self.assertEqual(noruns,
                                     [e for e in values if e in c])     
                self.assertEqual(result, list(cwr1(values, r)))         
                self.assertEqual(result, list(cwr2(values, r)))         

                for proto in range(pickle.HIGHEST_PROTOCOL + 1):
                    self.pickletest(proto, cwr(values,r))               

    @support.bigaddrspacetest
    def test_combinations_with_replacement_overflow(self):
        with self.assertRaises((OverflowError, MemoryError)):
            combinations_with_replacement("AA", 2**30)

        
    @support.impl_detail("tuple reuse is specific to CPython")
    def test_combinations_with_replacement_tuple_reuse(self):
        cwr = combinations_with_replacement
        self.assertEqual(len(set(map(id, cwr('abcde', 3)))), 1)
        self.assertNotEqual(len(set(map(id, list(cwr('abcde', 3))))), 1)

    @pickle_deprecated
    def test_permutations(self):
        self.assertRaises(TypeError, permutations)              
        self.assertRaises(TypeError, permutations, 'abc', 2, 1) 
        self.assertRaises(TypeError, permutations, None)        
        self.assertRaises(ValueError, permutations, 'abc', -2)  
        self.assertEqual(list(permutations('abc', 32)), [])     
        self.assertRaises(TypeError, permutations, 'abc', 's')  
        self.assertEqual(list(permutations(range(3), 2)),
                                           [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)])

        def permutations1(iterable, r=None):
            'Pure python version shown in the docs'
            pool = tuple(iterable)
            n = len(pool)
            r = n if r is None else r
            if r > n:
                return
            indices = list(range(n))
            cycles = list(range(n-r+1, n+1))[::-1]
            yield tuple(pool[i] for i in indices[:r])
            while n:
                for i in reversed(range(r)):
                    cycles[i] -= 1
                    if cycles[i] == 0:
                        indices[i:] = indices[i+1:] + indices[i:i+1]
                        cycles[i] = n - i
                    else:
                        j = cycles[i]
                        indices[i], indices[-j] = indices[-j], indices[i]
                        yield tuple(pool[i] for i in indices[:r])
                        break
                else:
                    return

        def permutations2(iterable, r=None):
            'Pure python version shown in the docs'
            pool = tuple(iterable)
            n = len(pool)
            r = n if r is None else r
            for indices in product(range(n), repeat=r):
                if len(set(indices)) == r:
                    yield tuple(pool[i] for i in indices)

        for n in range(7):
            values = [5*x-12 for x in range(n)]
            for r in range(n+2):
                result = list(permutations(values, r))
                self.assertEqual(len(result), 0 if r>n else fact(n) / fact(n-r))      
                self.assertEqual(len(result), len(set(result)))         
                self.assertEqual(result, sorted(result))                
                for p in result:
                    self.assertEqual(len(p), r)                         
                    self.assertEqual(len(set(p)), r)                    
                    self.assertTrue(all(e in values for e in p))           
                self.assertEqual(result, list(permutations1(values, r))) 
                self.assertEqual(result, list(permutations2(values, r))) 
                if r == n:
                    self.assertEqual(result, list(permutations(values, None))) 
                    self.assertEqual(result, list(permutations(values)))       

                for proto in range(pickle.HIGHEST_PROTOCOL + 1):
                    self.pickletest(proto, permutations(values, r))     

    @support.bigaddrspacetest
    def test_permutations_overflow(self):
        with self.assertRaises((OverflowError, MemoryError)):
            permutations("A", 2**30)

    @support.impl_detail("tuple reuse is specific to CPython")
    def test_permutations_tuple_reuse(self):
        self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1)
        self.assertNotEqual(len(set(map(id, list(permutations('abcde', 3))))), 1)

    def test_combinatorics(self):
        
        

        for n in range(6):
            s = 'ABCDEFG'[:n]
            for r in range(8):
                prod = list(product(s, repeat=r))
                cwr = list(combinations_with_replacement(s, r))
                perm = list(permutations(s, r))
                comb = list(combinations(s, r))

                
                self.assertEqual(len(prod), n**r)
                self.assertEqual(len(cwr), (fact(n+r-1) / fact(r)/ fact(n-1)) if n else (not r))
                self.assertEqual(len(perm), 0 if r>n else fact(n) / fact(n-r))
                self.assertEqual(len(comb), 0 if r>n else fact(n) / fact(r) / fact(n-r))

                
                self.assertEqual(prod, sorted(set(prod)))
                self.assertEqual(cwr, sorted(set(cwr)))
                self.assertEqual(perm, sorted(set(perm)))
                self.assertEqual(comb, sorted(set(comb)))

                
                self.assertEqual(cwr, [t for t in prod if sorted(t)==list(t)]) 
                self.assertEqual(perm, [t for t in prod if len(set(t))==r])    
                self.assertEqual(comb, [t for t in perm if sorted(t)==list(t)]) 
                self.assertEqual(comb, [t for t in cwr if len(set(t))==r])      
                self.assertEqual(comb, list(filter(set(cwr).__contains__, perm)))     
                self.assertEqual(comb, list(filter(set(perm).__contains__, cwr)))     
                self.assertEqual(comb, sorted(set(cwr) & set(perm)))            

    @pickle_deprecated
    def test_compress(self):
        self.assertEqual(list(compress(data='ABCDEF', selectors=[1,0,1,0,1,1])), list('ACEF'))
        self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
        self.assertEqual(list(compress('ABCDEF', [0,0,0,0,0,0])), list(''))
        self.assertEqual(list(compress('ABCDEF', [1,1,1,1,1,1])), list('ABCDEF'))
        self.assertEqual(list(compress('ABCDEF', [1,0,1])), list('AC'))
        self.assertEqual(list(compress('ABC', [0,1,1,1,1,1])), list('BC'))
        n = 10000
        data = chain.from_iterable(repeat(range(6), n))
        selectors = chain.from_iterable(repeat((0, 1)))
        self.assertEqual(list(compress(data, selectors)), [1,3,5] * n)
        self.assertRaises(TypeError, compress, None, range(6))      
        self.assertRaises(TypeError, compress, range(6), None)      
        self.assertRaises(TypeError, compress, range(6))            
        self.assertRaises(TypeError, compress, range(6), None)      

        
        for op in [lambda a:copy.copy(a), lambda a:copy.deepcopy(a)] + picklecopiers:
            for data, selectors, result1, result2 in [
                ('ABCDEF', [1,0,1,0,1,1], 'ACEF', 'CEF'),
                ('ABCDEF', [0,0,0,0,0,0], '', ''),
                ('ABCDEF', [1,1,1,1,1,1], 'ABCDEF', 'BCDEF'),
                ('ABCDEF', [1,0,1], 'AC', 'C'),
                ('ABC', [0,1,1,1,1,1], 'BC', 'C'),
                ]:

                self.assertEqual(list(op(compress(data=data, selectors=selectors))), list(result1))
                self.assertEqual(list(op(compress(data, selectors))), list(result1))
                testIntermediate = compress(data, selectors)
                if result1:
                    next(testIntermediate)
                    self.assertEqual(list(op(testIntermediate)), list(result2))

    @pickle_deprecated
    def test_count(self):
        self.assertEqual(lzip('abc',count()), [('a', 0), ('b', 1), ('c', 2)])
        self.assertEqual(lzip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)])
        self.assertEqual(take(2, lzip('abc',count(3))), [('a', 3), ('b', 4)])
        self.assertEqual(take(2, zip('abc',count(-1))), [('a', -1), ('b', 0)])
        self.assertEqual(take(2, zip('abc',count(-3))), [('a', -3), ('b', -2)])
        self.assertRaises(TypeError, count, 2, 3, 4)
        self.assertRaises(TypeError, count, 'a')
        self.assertEqual(take(10, count(maxsize-5)),
                         list(range(maxsize-5, maxsize+5)))
        self.assertEqual(take(10, count(-maxsize-5)),
                         list(range(-maxsize-5, -maxsize+5)))
        self.assertEqual(take(3, count(3.25)), [3.25, 4.25, 5.25])
        self.assertEqual(take(3, count(3.25-4j)), [3.25-4j, 4.25-4j, 5.25-4j])
        self.assertEqual(take(3, count(Decimal('1.1'))),
                         [Decimal('1.1'), Decimal('2.1'), Decimal('3.1')])
        self.assertEqual(take(3, count(Fraction(2, 3))),
                         [Fraction(2, 3), Fraction(5, 3), Fraction(8, 3)])
        BIGINT = 1<<1000
        self.assertEqual(take(3, count(BIGINT)), [BIGINT, BIGINT+1, BIGINT+2])
        c = count(3)
        self.assertEqual(repr(c), 'count(3)')
        next(c)
        self.assertEqual(repr(c), 'count(4)')
        c = count(-9)
        self.assertEqual(repr(c), 'count(-9)')
        next(c)
        self.assertEqual(next(c), -8)
        self.assertEqual(repr(count(10.25)), 'count(10.25)')
        self.assertEqual(repr(count(10.0)), 'count(10.0)')
        self.assertEqual(type(next(count(10.0))), float)
        for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5):
            
            r1 = repr(count(i))
            r2 = 'count(%r)'.__mod__(i)
            self.assertEqual(r1, r2)

        
        for value in -3, 3, maxsize-5, maxsize+5:
            c = count(value)
            self.assertEqual(next(copy.copy(c)), value)
            self.assertEqual(next(copy.deepcopy(c)), value)
            for proto in range(pickle.HIGHEST_PROTOCOL + 1):
                self.pickletest(proto, count(value))

        
        count(1, maxsize+5); sys.exc_info()

    @pickle_deprecated
    def test_count_with_stride(self):
        self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
        self.assertEqual(lzip('abc',count(start=2,step=3)),
                         [('a', 2), ('b', 5), ('c', 8)])
        self.assertEqual(lzip('abc',count(step=-1)),
                         [('a', 0), ('b', -1), ('c', -2)])
        self.assertRaises(TypeError, count, 'a', 'b')
        self.assertEqual(lzip('abc',count(2,0)), [('a', 2), ('b', 2), ('c', 2)])
        self.assertEqual(lzip('abc',count(2,1)), [('a', 2), ('b', 3), ('c', 4)])
        self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
        self.assertEqual(take(20, count(maxsize-15, 3)), take(20, range(maxsize-15, maxsize+100, 3)))
        self.assertEqual(take(20, count(-maxsize-15, 3)), take(20, range(-maxsize-15,-maxsize+100, 3)))
        self.assertEqual(take(3, count(10, maxsize+5)),
                         list(range(10, 10+3*(maxsize+5), maxsize+5)))
        self.assertEqual(take(3, count(2, 1.25)), [2, 3.25, 4.5])
        self.assertEqual(take(3, count(2, 3.25-4j)), [2, 5.25-4j, 8.5-8j])
        self.assertEqual(take(3, count(Decimal('1.1'), Decimal('.1'))),
                         [Decimal('1.1'), Decimal('1.2'), Decimal('1.3')])
        self.assertEqual(take(3, count(Fraction(2,3), Fraction(1,7))),
                         [Fraction(2,3), Fraction(17,21), Fraction(20,21)])
        BIGINT = 1<<1000
        self.assertEqual(take(3, count(step=BIGINT)), [0, BIGINT, 2*BIGINT])
        self.assertEqual(repr(take(3, count(10, 2.5))), repr([10, 12.5, 15.0]))
        c = count(3, 5)
        self.assertEqual(repr(c), 'count(3, 5)')
        next(c)
        self.assertEqual(repr(c), 'count(8, 5)')
        c = count(-9, 0)
        self.assertEqual(repr(c), 'count(-9, 0)')
        next(c)
        self.assertEqual(repr(c), 'count(-9, 0)')
        c = count(-9, -3)
        self.assertEqual(repr(c), 'count(-9, -3)')
        next(c)
        self.assertEqual(repr(c), 'count(-12, -3)')
        self.assertEqual(repr(c), 'count(-12, -3)')
        self.assertEqual(repr(count(10.5, 1.25)), 'count(10.5, 1.25)')
        self.assertEqual(repr(count(10.5, 1)), 'count(10.5)')           
        self.assertEqual(repr(count(10.5, 1.00)), 'count(10.5, 1.0)')   
        self.assertEqual(repr(count(10, 1.00)), 'count(10, 1.0)')
        c = count(10, 1.0)
        self.assertEqual(type(next(c)), int)
        self.assertEqual(type(next(c)), float)
        for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5):
            for j in  (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 1, 10, sys.maxsize-5, sys.maxsize+5):
                
                r1 = repr(count(i, j))
                if j == 1:
                    r2 = ('count(%r)' % i)
                else:
                    r2 = ('count(%r, %r)' % (i, j))
                self.assertEqual(r1, r2)
                for proto in range(pickle.HIGHEST_PROTOCOL + 1):
                    self.pickletest(proto, count(i, j))

    def test_cycle(self):
        self.assertEqual(take(10, cycle('abc')), list('abcabcabca'))
        self.assertEqual(list(cycle('')), [])
        self.assertRaises(TypeError, cycle)
        self.assertRaises(TypeError, cycle, 5)
        self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0])

    @pickle_deprecated
    def test_cycle_copy_pickle(self):
        
        c = cycle('abc')
        self.assertEqual(next(c), 'a')
        
        
        
        self.assertEqual(take(10, copy.deepcopy(c)), list('bcabcabcab'))
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            self.assertEqual(take(10, pickle.loads(pickle.dumps(c, proto))),
                             list('bcabcabcab'))
            next(c)
            self.assertEqual(take(10, pickle.loads(pickle.dumps(c, proto))),
                             list('cabcabcabc'))
            next(c)
            next(c)
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            self.pickletest(proto, cycle('abc'))

        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            
            it = iter('abcde')
            c = cycle(it)
            _ = [next(c) for i in range(2)]      
            p = pickle.dumps(c, proto)
            d = pickle.loads(p)                  
            self.assertEqual(take(20, d), list('cdeabcdeabcdeabcdeab'))

            
            it = iter('abcde')
            c = cycle(it)
            _ = [next(c) for i in range(7)]      
            p = pickle.dumps(c, proto)
            d = pickle.loads(p)                  
            self.assertEqual(take(20, d), list('cdeabcdeabcdeabcdeab'))

    @pickle_deprecated
    def test_cycle_unpickle_compat(self):
        testcases = [
            b'citertools\ncycle\n(c__builtin__\niter\n((lI1\naI2\naI3\natRI1\nbtR((lI1\naI0\ntb.',
            b'citertools\ncycle\n(c__builtin__\niter\n(](K\x01K\x02K\x03etRK\x01btR(]K\x01aK\x00tb.',
            b'\x80\x02citertools\ncycle\nc__builtin__\niter\n](K\x01K\x02K\x03e\x85RK\x01b\x85R]K\x01aK\x00\x86b.',
            b'\x80\x03citertools\ncycle\ncbuiltins\niter\n](K\x01K\x02K\x03e\x85RK\x01b\x85R]K\x01aK\x00\x86b.',
            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.',

            b'citertools\ncycle\n(c__builtin__\niter\n((lp0\nI1\naI2\naI3\natRI1\nbtR(g0\nI1\ntb.',
            b'citertools\ncycle\n(c__builtin__\niter\n(]q\x00(K\x01K\x02K\x03etRK\x01btR(h\x00K\x01tb.',
            b'\x80\x02citertools\ncycle\nc__builtin__\niter\n]q\x00(K\x01K\x02K\x03e\x85RK\x01b\x85Rh\x00K\x01\x86b.',
            b'\x80\x03citertools\ncycle\ncbuiltins\niter\n]q\x00(K\x01K\x02K\x03e\x85RK\x01b\x85Rh\x00K\x01\x86b.',
            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.',

            b'citertools\ncycle\n(c__builtin__\niter\n((lI1\naI2\naI3\natRI1\nbtR((lI1\naI00\ntb.',
            b'citertools\ncycle\n(c__builtin__\niter\n(](K\x01K\x02K\x03etRK\x01btR(]K\x01aI00\ntb.',
            b'\x80\x02citertools\ncycle\nc__builtin__\niter\n](K\x01K\x02K\x03e\x85RK\x01b\x85R]K\x01a\x89\x86b.',
            b'\x80\x03citertools\ncycle\ncbuiltins\niter\n](K\x01K\x02K\x03e\x85RK\x01b\x85R]K\x01a\x89\x86b.',
            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.',

            b'citertools\ncycle\n(c__builtin__\niter\n((lp0\nI1\naI2\naI3\natRI1\nbtR(g0\nI01\ntb.',
            b'citertools\ncycle\n(c__builtin__\niter\n(]q\x00(K\x01K\x02K\x03etRK\x01btR(h\x00I01\ntb.',
            b'\x80\x02citertools\ncycle\nc__builtin__\niter\n]q\x00(K\x01K\x02K\x03e\x85RK\x01b\x85Rh\x00\x88\x86b.',
            b'\x80\x03citertools\ncycle\ncbuiltins\niter\n]q\x00(K\x01K\x02K\x03e\x85RK\x01b\x85Rh\x00\x88\x86b.',
            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.',
        ]
        assert len(testcases) == 20
        for t in testcases:
            it = pickle.loads(t)
            self.assertEqual(take(10, it), [2, 3, 1, 2, 3, 1, 2, 3, 1, 2])

    @pickle_deprecated
    def test_cycle_setstate(self):
        

        
        
        
        
        c = cycle('defg')
        c.__setstate__((list('abc'), 0))
        self.assertEqual(take(20, c), list('defgabcdefgabcdefgab'))

        
        
        
        
        c = cycle('defg')
        c.__setstate__((list('abcdefg'), 1))
        self.assertEqual(take(20, c), list('defgabcdefgabcdefgab'))

        
        with self.assertRaises(TypeError):
            cycle('defg').__setstate__([list('abcdefg'), 0])

        
        with self.assertRaises(TypeError):
            c = cycle('defg')
            c.__setstate__((tuple('defg'), 0))
        take(20, c)

        
        with self.assertRaises(TypeError):
            cycle('defg').__setstate__((list('abcdefg'), 'x'))

        self.assertRaises(TypeError, cycle('').__setstate__, ())
        self.assertRaises(TypeError, cycle('').__setstate__, ([],))

    @pickle_deprecated
    def test_groupby(self):
        
        self.assertEqual([], list(groupby([])))
        self.assertEqual([], list(groupby([], key=id)))
        self.assertRaises(TypeError, list, groupby('abc', []))
        self.assertRaises(TypeError, groupby, None)
        self.assertRaises(TypeError, groupby, 'abc', lambda x:x, 10)

        
        s = [(0, 10, 20), (0, 11,21), (0,12,21), (1,13,21), (1,14,22),
             (2,15,22), (3,16,23), (3,17,23)]
        dup = []
        for k, g in groupby(s, lambda r:r[0]):
            for elem in g:
                self.assertEqual(k, elem[0])
                dup.append(elem)
        self.assertEqual(s, dup)

        
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            dup = []
            for k, g in pickle.loads(pickle.dumps(groupby(s, testR), proto)):
                for elem in g:
                    self.assertEqual(k, elem[0])
                    dup.append(elem)
            self.assertEqual(s, dup)

        
        dup = []
        for k, g in groupby(s, testR):
            for ik, ig in groupby(g, testR2):
                for elem in ig:
                    self.assertEqual(k, elem[0])
                    self.assertEqual(ik, elem[2])
                    dup.append(elem)
        self.assertEqual(s, dup)

        
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            dup = []
            for k, g in pickle.loads(pickle.dumps(groupby(s, testR), proto)):
                for ik, ig in pickle.loads(pickle.dumps(groupby(g, testR2), proto)):
                    for elem in ig:
                        self.assertEqual(k, elem[0])
                        self.assertEqual(ik, elem[2])
                        dup.append(elem)
            self.assertEqual(s, dup)


        
        keys = [k for k, g in groupby(s, testR)]
        expectedkeys = set([r[0] for r in s])
        self.assertEqual(set(keys), expectedkeys)
        self.assertEqual(len(keys), len(expectedkeys))

        
        
        s = list(zip('AABBBAAAA', range(9)))
        it = groupby(s, testR)
        _, g1 = next(it)
        _, g2 = next(it)
        _, g3 = next(it)
        self.assertEqual(list(g1), [])
        self.assertEqual(list(g2), [])
        self.assertEqual(next(g3), ('A', 5))
        list(it)  
        self.assertEqual(list(g3), [])

        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            it = groupby(s, testR)
            _, g = next(it)
            next(it)
            next(it)
            self.assertEqual(list(pickle.loads(pickle.dumps(g, proto))), [])

        
        s = 'abracadabra'
        
        r = [k for k, g in groupby(sorted(s))]
        self.assertEqual(r, ['a', 'b', 'c', 'd', 'r'])
        
        r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))]
        self.assertEqual(r, ['a', 'b', 'r'])
        
        r = [(len(list(g)), k) for k, g in groupby(sorted(s))]
        self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')])
        
        r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3]
        self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')])

        
        class ExpectedError(Exception):
            pass
        def delayed_raise(n=0):
            for i in range(n):
                yield 'yo'
            raise ExpectedError
        def gulp(iterable, keyp=None, func=list):
            return [func(g) for k, g in groupby(iterable, keyp)]

        
        self.assertRaises(ExpectedError, gulp, delayed_raise(0))
        
        self.assertRaises(ExpectedError, gulp, delayed_raise(1))

        
        class DummyCmp:
            def __eq__(self, dst):
                raise ExpectedError
        s = [DummyCmp(), DummyCmp(), None]

        
        self.assertRaises(ExpectedError, gulp, s, func=id)
        
        self.assertRaises(ExpectedError, gulp, s)

        
        def keyfunc(obj):
            if keyfunc.skip > 0:
                keyfunc.skip -= 1
                return obj
            else:
                raise ExpectedError

        
        keyfunc.skip = 0
        self.assertRaises(ExpectedError, gulp, [None], keyfunc)
        keyfunc.skip = 1
        self.assertRaises(ExpectedError, gulp, [None, None], keyfunc)

    def test_filter(self):
        self.assertEqual(list(filter(isEven, range(6))), [0,2,4])
        self.assertEqual(list(filter(None, [0,1,0,2,0])), [1,2])
        self.assertEqual(list(filter(bool, [0,1,0,2,0])), [1,2])
        self.assertEqual(take(4, filter(isEven, count())), [0,2,4,6])
        self.assertRaises(TypeError, filter)
        self.assertRaises(TypeError, filter, lambda x:x)
        self.assertRaises(TypeError, filter, lambda x:x, range(6), 7)
        self.assertRaises(TypeError, filter, isEven, 3)
        self.assertRaises(TypeError, next, filter(range(6), range(6)))

        
        ans = [0,2,4]

        c = filter(isEven, range(6))
        self.assertEqual(list(copy.copy(c)), ans)
        c = filter(isEven, range(6))
        self.assertEqual(list(copy.deepcopy(c)), ans)
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            c = filter(isEven, range(6))
            self.assertEqual(list(pickle.loads(pickle.dumps(c, proto))), ans)
            next(c)
            self.assertEqual(list(pickle.loads(pickle.dumps(c, proto))), ans[1:])
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            c = filter(isEven, range(6))
            self.pickletest(proto, c)

    @pickle_deprecated
    def test_filterfalse(self):
        self.assertEqual(list(filterfalse(isEven, range(6))), [1,3,5])
        self.assertEqual(list(filterfalse(None, [0,1,0,2,0])), [0,0,0])
        self.assertEqual(list(filterfalse(bool, [0,1,0,2,0])), [0,0,0])
        self.assertEqual(take(4, filterfalse(isEven, count())), [1,3,5,7])
        self.assertRaises(TypeError, filterfalse)
        self.assertRaises(TypeError, filterfalse, lambda x:x)
        self.assertRaises(TypeError, filterfalse, lambda x:x, range(6), 7)
        self.assertRaises(TypeError, filterfalse, isEven, 3)
        self.assertRaises(TypeError, next, filterfalse(range(6), range(6)))
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            self.pickletest(proto, filterfalse(isEven, range(6)))

    def test_zip(self):
        
        ans = [(x,y) for x, y in zip('abc',count())]
        self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
        self.assertEqual(list(zip('abc', range(6))), lzip('abc', range(6)))
        self.assertEqual(list(zip('abcdef', range(3))), lzip('abcdef', range(3)))
        self.assertEqual(take(3,zip('abcdef', count())), lzip('abcdef', range(3)))
        self.assertEqual(list(zip('abcdef')), lzip('abcdef'))
        self.assertEqual(list(zip()), lzip())
        self.assertRaises(TypeError, zip, 3)
        self.assertRaises(TypeError, zip, range(3), 3)
        self.assertEqual([tuple(list(pair)) for pair in zip('abc', 'def')],
                         lzip('abc', 'def'))
        self.assertEqual([pair for pair in zip('abc', 'def')],
                         lzip('abc', 'def'))

    @support.impl_detail("tuple reuse is specific to CPython")
    @pickle_deprecated
    def test_zip_tuple_reuse(self):
        ids = list(map(id, zip('abc', 'def')))
        self.assertEqual(min(ids), max(ids))
        ids = list(map(id, list(zip('abc', 'def'))))
        self.assertEqual(len(dict.fromkeys(ids)), len(ids))

        
        ans = [(x,y) for x, y in copy.copy(zip('abc',count()))]
        self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])

        ans = [(x,y) for x, y in copy.deepcopy(zip('abc',count()))]
        self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])

        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            ans = [(x,y) for x, y in pickle.loads(pickle.dumps(zip('abc',count()), proto))]
            self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])

        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            testIntermediate = zip('abc',count())
            next(testIntermediate)
            ans = [(x,y) for x, y in pickle.loads(pickle.dumps(testIntermediate, proto))]
            self.assertEqual(ans, [('b', 1), ('c', 2)])

        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            self.pickletest(proto, zip('abc', count()))

    def test_ziplongest(self):
        for args in [
                ['abc', range(6)],
                [range(6), 'abc'],
                [range(1000), range(2000,2100), range(3000,3050)],
                [range(1000), range(0), range(3000,3050), range(1200), range(1500)],
                [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
            ]:
            target = [tuple([arg[i] if i < len(arg) else None for arg in args])
                      for i in range(max(map(len, args)))]
            self.assertEqual(list(zip_longest(*args)), target)
            self.assertEqual(list(zip_longest(*args, **{})), target)
            target = [tuple((e is None and 'X' or e) for e in t) for t in target]   
            self.assertEqual(list(zip_longest(*args, **dict(fillvalue='X'))), target)

        self.assertEqual(take(3,zip_longest('abcdef', count())), list(zip('abcdef', range(3)))) 

        self.assertEqual(list(zip_longest()), list(zip()))
        self.assertEqual(list(zip_longest([])), list(zip([])))
        self.assertEqual(list(zip_longest('abcdef')), list(zip('abcdef')))

        self.assertEqual(list(zip_longest('abc', 'defg', **{})),
                         list(zip(list('abc')+[None], 'defg'))) 
        self.assertRaises(TypeError, zip_longest, 3)
        self.assertRaises(TypeError, zip_longest, range(3), 3)

        for stmt in [
            "zip_longest('abc', fv=1)",
            "zip_longest('abc', fillvalue=1, bogus_keyword=None)",
        ]:
            try:
                eval(stmt, globals(), locals())
            except TypeError:
                pass
            else:
                self.fail('Did not raise Type in:  ' + stmt)

        self.assertEqual([tuple(list(pair)) for pair in zip_longest('abc', 'def')],
                         list(zip('abc', 'def')))
        self.assertEqual([pair for pair in zip_longest('abc', 'def')],
                         list(zip('abc', 'def')))

    @support.impl_detail("tuple reuse is specific to CPython")
    def test_zip_longest_tuple_reuse(self):
        ids = list(map(id, zip_longest('abc', 'def')))
        self.assertEqual(min(ids), max(ids))
        ids = list(map(id, list(zip_longest('abc', 'def'))))
        self.assertEqual(len(dict.fromkeys(ids)), len(ids))

    @pickle_deprecated
    def test_zip_longest_pickling(self):
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            self.pickletest(proto, zip_longest("abc", "def"))
            self.pickletest(proto, zip_longest("abc", "defgh"))
            self.pickletest(proto, zip_longest("abc", "defgh", fillvalue=1))
            self.pickletest(proto, zip_longest("", "defgh"))

    def test_zip_longest_bad_iterable(self):
        exception = TypeError()

        class BadIterable:
            def __iter__(self):
                raise exception

        with self.assertRaises(TypeError) as cm:
            zip_longest(BadIterable())

        self.assertIs(cm.exception, exception)

    def test_bug_7244(self):

        class Repeater:
            
            def __init__(self, o, t, e):
                self.o = o
                self.t = int(t)
                self.e = e
            def __iter__(self): 
                return self
            def __next__(self):
                if self.t > 0:
                    self.t -= 1
                    return self.o
                else:
                    raise self.e

        
        
        r1 = Repeater(1, 3, StopIteration)
        r2 = Repeater(2, 4, StopIteration)
        def run(r1, r2):
            result = []
            for i, j in zip_longest(r1, r2, fillvalue=0):
                with support.captured_output('stdout'):
                    print((i, j))
                result.append((i, j))
            return result
        self.assertEqual(run(r1, r2), [(1,2), (1,2), (1,2), (0,2)])

        
        
        r1 = Repeater(1, 3, RuntimeError)
        r2 = Repeater(2, 4, StopIteration)
        it = zip_longest(r1, r2, fillvalue=0)
        self.assertEqual(next(it), (1, 2))
        self.assertEqual(next(it), (1, 2))
        self.assertEqual(next(it), (1, 2))
        self.assertRaises(RuntimeError, next, it)

    def test_pairwise(self):
        self.assertEqual(list(pairwise('')), [])
        self.assertEqual(list(pairwise('a')), [])
        self.assertEqual(list(pairwise('ab')),
                              [('a', 'b')]),
        self.assertEqual(list(pairwise('abcde')),
                              [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')])
        self.assertEqual(list(pairwise(range(10_000))),
                         list(zip(range(10_000), range(1, 10_000))))

        with self.assertRaises(TypeError):
            pairwise()                                      
        with self.assertRaises(TypeError):
            pairwise('abc', 10)                             
        with self.assertRaises(TypeError):
            pairwise(iterable='abc')                        
        with self.assertRaises(TypeError):
            pairwise(None)                                  

    def test_product(self):
        for args, result in [
            ([], [()]),                     
            (['ab'], [('a',), ('b',)]),     
            ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]),     
            ([range(0), range(2), range(3)], []),           
            ([range(2), range(0), range(3)], []),           
            ([range(2), range(3), range(0)], []),           
            ]:
            self.assertEqual(list(product(*args)), result)
            for r in range(4):
                self.assertEqual(list(product(*(args*r))),
                                 list(product(*args, **dict(repeat=r))))
        self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
        self.assertRaises(TypeError, product, range(6), None)

        def product1(*args, **kwds):
            pools = list(map(tuple, args)) * kwds.get('repeat', 1)
            n = len(pools)
            if n == 0:
                yield ()
                return
            if any(len(pool) == 0 for pool in pools):
                return
            indices = [0] * n
            yield tuple(pool[i] for pool, i in zip(pools, indices))
            while 1:
                for i in reversed(range(n)):  
                    if indices[i] == len(pools[i]) - 1:
                        continue
                    indices[i] += 1
                    for j in range(i+1, n):
                        indices[j] = 0
                    yield tuple(pool[i] for pool, i in zip(pools, indices))
                    break
                else:
                    return

        def product2(*args, **kwds):
            'Pure python version used in docs'
            pools = list(map(tuple, args)) * kwds.get('repeat', 1)
            result = [[]]
            for pool in pools:
                result = [x+[y] for x in result for y in pool]
            for prod in result:
                yield tuple(prod)

        argtypes = ['', 'abc', '', range(0), range(4), dict(a=1, b=2, c=3),
                    set('abcdefg'), range(11), tuple(range(13))]
        for i in range(100):
            args = [random.choice(argtypes) for j in range(random.randrange(5))]
            expected_len = prod(map(len, args))
            self.assertEqual(len(list(product(*args))), expected_len)
            self.assertEqual(list(product(*args)), list(product1(*args)))
            self.assertEqual(list(product(*args)), list(product2(*args)))
            args = map(iter, args)
            self.assertEqual(len(list(product(*args))), expected_len)

    @support.bigaddrspacetest
    def test_product_overflow(self):
        with self.assertRaises((OverflowError, MemoryError)):
            product(*(['ab']*2**5), repeat=2**25)

    @support.impl_detail("tuple reuse is specific to CPython")
    def test_product_tuple_reuse(self):
        self.assertEqual(len(set(map(id, product('abc', 'def')))), 1)
        self.assertNotEqual(len(set(map(id, list(product('abc', 'def'))))), 1)

    @pickle_deprecated
    def test_product_pickling(self):
        
        for args, result in [
            ([], [()]),                     
            (['ab'], [('a',), ('b',)]),     
            ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]),     
            ([range(0), range(2), range(3)], []),           
            ([range(2), range(0), range(3)], []),           
            ([range(2), range(3), range(0)], []),           
            ]:
            self.assertEqual(list(copy.copy(product(*args))), result)
            self.assertEqual(list(copy.deepcopy(product(*args))), result)
            for proto in range(pickle.HIGHEST_PROTOCOL + 1):
                self.pickletest(proto, product(*args))

    @pickle_deprecated
    def test_product_issue_25021(self):
        
        p = product((1, 2),(3,))
        p.__setstate__((0, 0x1000))  
        self.assertEqual(next(p), (2, 3))
        
        p = product((1, 2), (), (3,))
        p.__setstate__((0, 0, 0x1000))  
        self.assertRaises(StopIteration, next, p)

    @pickle_deprecated
    def test_repeat(self):
        self.assertEqual(list(repeat(object='a', times=3)), ['a', 'a', 'a'])
        self.assertEqual(lzip(range(3),repeat('a')),
                         [(0, 'a'), (1, 'a'), (2, 'a')])
        self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
        self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
        self.assertEqual(list(repeat('a', 0)), [])
        self.assertEqual(list(repeat('a', -3)), [])
        self.assertRaises(TypeError, repeat)
        self.assertRaises(TypeError, repeat, None, 3, 4)
        self.assertRaises(TypeError, repeat, None, 'a')
        r = repeat(1+0j)
        self.assertEqual(repr(r), 'repeat((1+0j))')
        r = repeat(1+0j, 5)
        self.assertEqual(repr(r), 'repeat((1+0j), 5)')
        list(r)
        self.assertEqual(repr(r), 'repeat((1+0j), 0)')

        
        c = repeat(object='a', times=10)
        self.assertEqual(next(c), 'a')
        self.assertEqual(take(2, copy.copy(c)), list('a' * 2))
        self.assertEqual(take(2, copy.deepcopy(c)), list('a' * 2))
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            self.pickletest(proto, repeat(object='a', times=10))

    def test_repeat_with_negative_times(self):
        self.assertEqual(repr(repeat('a', -1)), "repeat('a', 0)")
        self.assertEqual(repr(repeat('a', -2)), "repeat('a', 0)")
        self.assertEqual(repr(repeat('a', times=-1)), "repeat('a', 0)")
        self.assertEqual(repr(repeat('a', times=-2)), "repeat('a', 0)")

    @pickle_deprecated
    def test_map(self):
        self.assertEqual(list(map(operator.pow, range(3), range(1,7))),
                         [0**1, 1**2, 2**3])
        self.assertEqual(list(map(tupleize, 'abc', range(5))),
                         [('a',0),('b',1),('c',2)])
        self.assertEqual(list(map(tupleize, 'abc', count())),
                         [('a',0),('b',1),('c',2)])
        self.assertEqual(take(2,map(tupleize, 'abc', count())),
                         [('a',0),('b',1)])
        self.assertEqual(list(map(operator.pow, [])), [])
        self.assertRaises(TypeError, map)
        self.assertRaises(TypeError, list, map(None, range(3), range(3)))
        self.assertRaises(TypeError, map, operator.neg)
        self.assertRaises(TypeError, next, map(10, range(5)))
        self.assertRaises(ValueError, next, map(errfunc, [4], [5]))
        self.assertRaises(TypeError, next, map(onearg, [4], [5]))

        
        ans = [('a',0),('b',1),('c',2)]

        c = map(tupleize, 'abc', count())
        self.assertEqual(list(copy.copy(c)), ans)

        c = map(tupleize, 'abc', count())
        self.assertEqual(list(copy.deepcopy(c)), ans)

        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            c = map(tupleize, 'abc', count())
            self.pickletest(proto, c)

    @pickle_deprecated
    def test_starmap(self):
        self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
                         [0**1, 1**2, 2**3])
        self.assertEqual(take(3, starmap(operator.pow, zip(count(), count(1)))),
                         [0**1, 1**2, 2**3])
        self.assertEqual(list(starmap(operator.pow, [])), [])
        self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5])
        self.assertRaises(TypeError, list, starmap(operator.pow, [None]))
        self.assertRaises(TypeError, starmap)
        self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
        self.assertRaises(TypeError, next, starmap(10, [(4,5)]))
        self.assertRaises(ValueError, next, starmap(errfunc, [(4,5)]))
        self.assertRaises(TypeError, next, starmap(onearg, [(4,5)]))

        
        ans = [0**1, 1**2, 2**3]

        c = starmap(operator.pow, zip(range(3), range(1,7)))
        self.assertEqual(list(copy.copy(c)), ans)

        c = starmap(operator.pow, zip(range(3), range(1,7)))
        self.assertEqual(list(copy.deepcopy(c)), ans)

        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            c = starmap(operator.pow, zip(range(3), range(1,7)))
            self.pickletest(proto, c)

    @pickle_deprecated
    def test_islice(self):
        for args in [          
                (10, 20, 3),
                (10, 3, 20),
                (10, 20),
                (10, 10),
                (10, 3),
                (20,)
                ]:
            self.assertEqual(list(islice(range(100), *args)),
                             list(range(*args)))

        for args, tgtargs in [  
                ((10, 110, 3), ((10, 100, 3))),
                ((10, 110), ((10, 100))),
                ((110,), (100,))
                ]:
            self.assertEqual(list(islice(range(100), *args)),
                             list(range(*tgtargs)))

        
        self.assertEqual(list(islice(range(10), None)), list(range(10)))
        self.assertEqual(list(islice(range(10), None, None)), list(range(10)))
        self.assertEqual(list(islice(range(10), None, None, None)), list(range(10)))
        self.assertEqual(list(islice(range(10), 2, None)), list(range(2, 10)))
        self.assertEqual(list(islice(range(10), 1, None, 2)), list(range(1, 10, 2)))

        
        it = iter(range(10))
        self.assertEqual(list(islice(it, 3)), list(range(3)))
        self.assertEqual(list(it), list(range(3, 10)))

        it = iter(range(10))
        self.assertEqual(list(islice(it, 3, 3)), [])
        self.assertEqual(list(it), list(range(3, 10)))

        
        ra = range(10)
        self.assertRaises(TypeError, islice, ra)
        self.assertRaises(TypeError, islice, ra, 1, 2, 3, 4)
        self.assertRaises(ValueError, islice, ra, -5, 10, 1)
        self.assertRaises(ValueError, islice, ra, 1, -5, -1)
        self.assertRaises(ValueError, islice, ra, 1, 10, -1)
        self.assertRaises(ValueError, islice, ra, 1, 10, 0)
        self.assertRaises(ValueError, islice, ra, 'a')
        self.assertRaises(ValueError, islice, ra, 'a', 1)
        self.assertRaises(ValueError, islice, ra, 1, 'a')
        self.assertRaises(ValueError, islice, ra, 'a', 1, 1)
        self.assertRaises(ValueError, islice, ra, 1, 'a', 1)
        self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)

        
        c = count()
        self.assertEqual(list(islice(c, 1, 3, 50)), [1])
        self.assertEqual(next(c), 3)

        
        for args in [          
                (10, 20, 3),
                (10, 3, 20),
                (10, 20),
                (10, 3),
                (20,)
                ]:
            self.assertEqual(list(copy.copy(islice(range(100), *args))),
                             list(range(*args)))
            self.assertEqual(list(copy.deepcopy(islice(range(100), *args))),
                             list(range(*args)))
            for proto in range(pickle.HIGHEST_PROTOCOL + 1):
                self.pickletest(proto, islice(range(100), *args))

        
        
        it = (x for x in (1, 2))
        wr = weakref.ref(it)
        it = islice(it, 1)
        self.assertIsNotNone(wr())
        list(it) 
        support.gc_collect()
        self.assertIsNone(wr())

        
        
        class IntLike(object):
            def __init__(self, val):
                self.val = val
            def __index__(self):
                return self.val
        self.assertEqual(list(islice(range(100), IntLike(10))), list(range(10)))
        self.assertEqual(list(islice(range(100), IntLike(10), IntLike(50))),
                         list(range(10, 50)))
        self.assertEqual(list(islice(range(100), IntLike(10), IntLike(50), IntLike(5))),
                         list(range(10,50,5)))

    @pickle_deprecated
    def test_takewhile(self):
        data = [1, 3, 5, 20, 2, 4, 6, 8]
        self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
        self.assertEqual(list(takewhile(underten, [])), [])
        self.assertRaises(TypeError, takewhile)
        self.assertRaises(TypeError, takewhile, operator.pow)
        self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
        self.assertRaises(TypeError, next, takewhile(10, [(4,5)]))
        self.assertRaises(ValueError, next, takewhile(errfunc, [(4,5)]))
        t = takewhile(bool, [1, 1, 1, 0, 0, 0])
        self.assertEqual(list(t), [1, 1, 1])
        self.assertRaises(StopIteration, next, t)

        
        self.assertEqual(list(copy.copy(takewhile(underten, data))), [1, 3, 5])
        self.assertEqual(list(copy.deepcopy(takewhile(underten, data))),
                        [1, 3, 5])
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            self.pickletest(proto, takewhile(underten, data))

    @pickle_deprecated
    def test_dropwhile(self):
        data = [1, 3, 5, 20, 2, 4, 6, 8]
        self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
        self.assertEqual(list(dropwhile(underten, [])), [])
        self.assertRaises(TypeError, dropwhile)
        self.assertRaises(TypeError, dropwhile, operator.pow)
        self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
        self.assertRaises(TypeError, next, dropwhile(10, [(4,5)]))
        self.assertRaises(ValueError, next, dropwhile(errfunc, [(4,5)]))

        
        self.assertEqual(list(copy.copy(dropwhile(underten, data))), [20, 2, 4, 6, 8])
        self.assertEqual(list(copy.deepcopy(dropwhile(underten, data))),
                        [20, 2, 4, 6, 8])
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            self.pickletest(proto, dropwhile(underten, data))

    @pickle_deprecated
    def test_tee(self):
        n = 200

        a, b = tee([])        
        self.assertEqual(list(a), [])
        self.assertEqual(list(b), [])

        a, b = tee(irange(n)) 
        self.assertEqual(lzip(a,b), lzip(range(n), range(n)))

        a, b = tee(irange(n)) 
        self.assertEqual(list(a), list(range(n)))
        self.assertEqual(list(b), list(range(n)))

        a, b = tee(irange(n)) 
        for i in range(100):
            self.assertEqual(next(a), i)
        del a
        self.assertEqual(list(b), list(range(n)))

        a, b = tee(irange(n)) 
        for i in range(100):
            self.assertEqual(next(a), i)
        del b
        self.assertEqual(list(a), list(range(100, n)))

        for j in range(5):   
            order = [0]*n + [1]*n
            random.shuffle(order)
            lists = ([], [])
            its = tee(irange(n))
            for i in order:
                value = next(its[i])
                lists[i].append(value)
            self.assertEqual(lists[0], list(range(n)))
            self.assertEqual(lists[1], list(range(n)))

        
        self.assertRaises(TypeError, tee)
        self.assertRaises(TypeError, tee, 3)
        self.assertRaises(TypeError, tee, [1,2], 'x')
        self.assertRaises(TypeError, tee, [1,2], 3, 'x')

        
        a, b = tee('abc')
        c = type(a)('def')
        self.assertEqual(list(c), list('def'))

        
        a, b, c = tee(range(2000), 3)
        for i in range(100):
            self.assertEqual(next(a), i)
        self.assertEqual(list(b), list(range(2000)))
        self.assertEqual([next(c), next(c)], list(range(2)))
        self.assertEqual(list(a), list(range(100,2000)))
        self.assertEqual(list(c), list(range(2,2000)))

        
        self.assertRaises(TypeError, tee, 'abc', 'invalid')
        self.assertRaises(ValueError, tee, [], -1)
        for n in range(5):
            result = tee('abc', n)
            self.assertEqual(type(result), tuple)
            self.assertEqual(len(result), n)
            self.assertEqual([list(x) for x in result], [list('abc')]*n)

        
        a, b = tee('abc')
        c, d = tee(a)
        self.assertTrue(a is c)

        
        t1, t2 = tee('abc')
        tnew = type(t1)
        self.assertRaises(TypeError, tnew)
        self.assertRaises(TypeError, tnew, 10)
        t3 = tnew(t1)
        self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc'))

        
        a, b = tee(range(10))
        p = weakref.proxy(a)
        self.assertEqual(getattr(p, '__class__'), type(b))
        del a
        support.gc_collect()  
        self.assertRaises(ReferenceError, getattr, p, '__class__')

        ans = list('abc')
        long_ans = list(range(10000))

        
        a, b = tee('abc')
        self.assertEqual(list(copy.copy(a)), ans)
        self.assertEqual(list(copy.copy(b)), ans)
        a, b = tee(list(range(10000)))
        self.assertEqual(list(copy.copy(a)), long_ans)
        self.assertEqual(list(copy.copy(b)), long_ans)

        
        a, b = tee('abc')
        take(2, a)
        take(1, b)
        self.assertEqual(list(copy.copy(a)), ans[2:])
        self.assertEqual(list(copy.copy(b)), ans[1:])
        self.assertEqual(list(a), ans[2:])
        self.assertEqual(list(b), ans[1:])
        a, b = tee(range(10000))
        take(100, a)
        take(60, b)
        self.assertEqual(list(copy.copy(a)), long_ans[100:])
        self.assertEqual(list(copy.copy(b)), long_ans[60:])
        self.assertEqual(list(a), long_ans[100:])
        self.assertEqual(list(b), long_ans[60:])

        
        a, b = tee('abc')
        self.assertEqual(list(copy.deepcopy(a)), ans)
        self.assertEqual(list(copy.deepcopy(b)), ans)
        self.assertEqual(list(a), ans)
        self.assertEqual(list(b), ans)
        a, b = tee(range(10000))
        self.assertEqual(list(copy.deepcopy(a)), long_ans)
        self.assertEqual(list(copy.deepcopy(b)), long_ans)
        self.assertEqual(list(a), long_ans)
        self.assertEqual(list(b), long_ans)

        
        a, b = tee('abc')
        take(2, a)
        take(1, b)
        self.assertEqual(list(copy.deepcopy(a)), ans[2:])
        self.assertEqual(list(copy.deepcopy(b)), ans[1:])
        self.assertEqual(list(a), ans[2:])
        self.assertEqual(list(b), ans[1:])
        a, b = tee(range(10000))
        take(100, a)
        take(60, b)
        self.assertEqual(list(copy.deepcopy(a)), long_ans[100:])
        self.assertEqual(list(copy.deepcopy(b)), long_ans[60:])
        self.assertEqual(list(a), long_ans[100:])
        self.assertEqual(list(b), long_ans[60:])

        
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            self.pickletest(proto, iter(tee('abc')))
            a, b = tee('abc')
            self.pickletest(proto, a, compare=ans)
            self.pickletest(proto, b, compare=ans)

    
    def test_tee_del_backward(self):
        forward, backward = tee(repeat(None, 20000000))
        try:
            any(forward)  
            del backward
        except:
            del forward, backward
            raise

    def test_tee_reenter(self):
        class I:
            first = True
            def __iter__(self):
                return self
            def __next__(self):
                first = self.first
                self.first = False
                if first:
                    return next(b)

        a, b = tee(I())
        with self.assertRaisesRegex(RuntimeError, "tee"):
            next(a)

    @threading_helper.requires_working_threading()
    def test_tee_concurrent(self):
        start = threading.Event()
        finish = threading.Event()
        class I:
            def __iter__(self):
                return self
            def __next__(self):
                start.set()
                finish.wait()

        a, b = tee(I())
        thread = threading.Thread(target=next, args=[a])
        thread.start()
        try:
            start.wait()
            with self.assertRaisesRegex(RuntimeError, "tee"):
                next(b)
        finally:
            finish.set()
            thread.join()

    def test_StopIteration(self):
        self.assertRaises(StopIteration, next, zip())

        for f in (chain, cycle, zip, groupby):
            self.assertRaises(StopIteration, next, f([]))
            self.assertRaises(StopIteration, next, f(StopNow()))

        self.assertRaises(StopIteration, next, islice([], None))
        self.assertRaises(StopIteration, next, islice(StopNow(), None))

        p, q = tee([])
        self.assertRaises(StopIteration, next, p)
        self.assertRaises(StopIteration, next, q)
        p, q = tee(StopNow())
        self.assertRaises(StopIteration, next, p)
        self.assertRaises(StopIteration, next, q)

        self.assertRaises(StopIteration, next, repeat(None, 0))

        for f in (filter, filterfalse, map, takewhile, dropwhile, starmap):
            self.assertRaises(StopIteration, next, f(lambda x:x, []))
            self.assertRaises(StopIteration, next, f(lambda x:x, StopNow()))

    @support.cpython_only
    def test_combinations_result_gc(self):
        
        
        
        it = combinations([None, []], 1)
        next(it)
        gc.collect()
        
        
        
        self.assertTrue(gc.is_tracked(next(it)))

    @support.cpython_only
    def test_combinations_with_replacement_result_gc(self):
        
        it = combinations_with_replacement([None, []], 1)
        next(it)
        gc.collect()
        self.assertTrue(gc.is_tracked(next(it)))

    @support.cpython_only
    def test_permutations_result_gc(self):
        
        it = permutations([None, []], 1)
        next(it)
        gc.collect()
        self.assertTrue(gc.is_tracked(next(it)))

    @support.cpython_only
    def test_product_result_gc(self):
        
        it = product([None, []])
        next(it)
        gc.collect()
        self.assertTrue(gc.is_tracked(next(it)))

    @support.cpython_only
    def test_zip_longest_result_gc(self):
        
        it = zip_longest([[]])
        gc.collect()
        self.assertTrue(gc.is_tracked(next(it)))

    @support.cpython_only
    def test_immutable_types(self):
        from itertools import _grouper, _tee, _tee_dataobject
        dataset = (
            accumulate,
            batched,
            chain,
            combinations,
            combinations_with_replacement,
            compress,
            count,
            cycle,
            dropwhile,
            filterfalse,
            groupby,
            _grouper,
            islice,
            pairwise,
            permutations,
            product,
            repeat,
            starmap,
            takewhile,
            _tee,
            _tee_dataobject,
            zip_longest,
        )
        for tp in dataset:
            with self.subTest(tp=tp):
                with self.assertRaisesRegex(TypeError, "immutable"):
                    tp.foobar = 1


class TestExamples(unittest.TestCase):

    def test_accumulate(self):
        self.assertEqual(list(accumulate([1,2,3,4,5])), [1, 3, 6, 10, 15])

    @pickle_deprecated
    def test_accumulate_reducible(self):
        
        data = [1, 2, 3, 4, 5]
        accumulated = [1, 3, 6, 10, 15]

        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            it = accumulate(data)
            self.assertEqual(list(pickle.loads(pickle.dumps(it, proto))), accumulated[:])
            self.assertEqual(next(it), 1)
            self.assertEqual(list(pickle.loads(pickle.dumps(it, proto))), accumulated[1:])
        it = accumulate(data)
        self.assertEqual(next(it), 1)
        self.assertEqual(list(copy.deepcopy(it)), accumulated[1:])
        self.assertEqual(list(copy.copy(it)), accumulated[1:])

    @pickle_deprecated
    def test_accumulate_reducible_none(self):
        
        it = accumulate([None, None, None], operator.is_)
        self.assertEqual(next(it), None)
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            it_copy = pickle.loads(pickle.dumps(it, proto))
            self.assertEqual(list(it_copy), [True, False])
        self.assertEqual(list(copy.deepcopy(it)), [True, False])
        self.assertEqual(list(copy.copy(it)), [True, False])

    def test_chain(self):
        self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF')

    def test_chain_from_iterable(self):
        self.assertEqual(''.join(chain.from_iterable(['ABC', 'DEF'])), 'ABCDEF')

    def test_combinations(self):
        self.assertEqual(list(combinations('ABCD', 2)),
                         [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
        self.assertEqual(list(combinations(range(4), 3)),
                         [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])

    def test_combinations_with_replacement(self):
        self.assertEqual(list(combinations_with_replacement('ABC', 2)),
                         [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])

    def test_compress(self):
        self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))

    def test_count(self):
        self.assertEqual(list(islice(count(10), 5)), [10, 11, 12, 13, 14])

    def test_cycle(self):
        self.assertEqual(list(islice(cycle('ABCD'), 12)), list('ABCDABCDABCD'))

    def test_dropwhile(self):
        self.assertEqual(list(dropwhile(lambda x: x<5, [1,4,6,4,1])), [6,4,1])

    def test_groupby(self):
        self.assertEqual([k for k, g in groupby('AAAABBBCCDAABBB')],
                         list('ABCDAB'))
        self.assertEqual([(list(g)) for k, g in groupby('AAAABBBCCD')],
                         [list('AAAA'), list('BBB'), list('CC'), list('D')])

    def test_filter(self):
        self.assertEqual(list(filter(lambda x: x%2, range(10))), [1,3,5,7,9])

    def test_filterfalse(self):
        self.assertEqual(list(filterfalse(lambda x: x%2, range(10))), [0,2,4,6,8])

    def test_map(self):
        self.assertEqual(list(map(pow, (2,3,10), (5,2,3))), [32, 9, 1000])

    def test_islice(self):
        self.assertEqual(list(islice('ABCDEFG', 2)), list('AB'))
        self.assertEqual(list(islice('ABCDEFG', 2, 4)), list('CD'))
        self.assertEqual(list(islice('ABCDEFG', 2, None)), list('CDEFG'))
        self.assertEqual(list(islice('ABCDEFG', 0, None, 2)), list('ACEG'))

    def test_zip(self):
        self.assertEqual(list(zip('ABCD', 'xy')), [('A', 'x'), ('B', 'y')])

    def test_zip_longest(self):
        self.assertEqual(list(zip_longest('ABCD', 'xy', fillvalue='-')),
                         [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')])

    def test_permutations(self):
        self.assertEqual(list(permutations('ABCD', 2)),
                         list(map(tuple, 'AB AC AD BA BC BD CA CB CD DA DB DC'.split())))
        self.assertEqual(list(permutations(range(3))),
                         [(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0)])

    def test_product(self):
        self.assertEqual(list(product('ABCD', 'xy')),
                         list(map(tuple, 'Ax Ay Bx By Cx Cy Dx Dy'.split())))
        self.assertEqual(list(product(range(2), repeat=3)),
                        [(0,0,0), (0,0,1), (0,1,0), (0,1,1),
                         (1,0,0), (1,0,1), (1,1,0), (1,1,1)])

    def test_repeat(self):
        self.assertEqual(list(repeat(10, 3)), [10, 10, 10])

    def test_stapmap(self):
        self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])),
                         [32, 9, 1000])

    def test_takewhile(self):
        self.assertEqual(list(takewhile(lambda x: x<5, [1,4,6,4,1])), [1,4])


class TestPurePythonRoughEquivalents(unittest.TestCase):

    def test_batched_recipe(self):
        def batched_recipe(iterable, n):
            "Batch data into tuples of length n. The last batch may be shorter."
            
            if n < 1:
                raise ValueError('n must be at least one')
            it = iter(iterable)
            while batch := tuple(islice(it, n)):
                yield batch

        for iterable, n in product(
                ['', 'a', 'ab', 'abc', 'abcd', 'abcde', 'abcdef', 'abcdefg', None],
                [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, None]):
            with self.subTest(iterable=iterable, n=n):
                try:
                    e1, r1 = None, list(batched(iterable, n))
                except Exception as e:
                    e1, r1 = type(e), None
                try:
                    e2, r2 = None, list(batched_recipe(iterable, n))
                except Exception as e:
                    e2, r2 = type(e), None
                self.assertEqual(r1, r2)
                self.assertEqual(e1, e2)

    @staticmethod
    def islice(iterable, *args):
        s = slice(*args)
        start, stop, step = s.start or 0, s.stop or sys.maxsize, s.step or 1
        it = iter(range(start, stop, step))
        try:
            nexti = next(it)
        except StopIteration:
            
            for i, element in zip(range(start), iterable):
                pass
            return
        try:
            for i, element in enumerate(iterable):
                if i == nexti:
                    yield element
                    nexti = next(it)
        except StopIteration:
            
            for i, element in zip(range(i + 1, stop), iterable):
                pass

    def test_islice_recipe(self):
        self.assertEqual(list(self.islice('ABCDEFG', 2)), list('AB'))
        self.assertEqual(list(self.islice('ABCDEFG', 2, 4)), list('CD'))
        self.assertEqual(list(self.islice('ABCDEFG', 2, None)), list('CDEFG'))
        self.assertEqual(list(self.islice('ABCDEFG', 0, None, 2)), list('ACEG'))
        
        it = iter(range(10))
        self.assertEqual(list(self.islice(it, 3)), list(range(3)))
        self.assertEqual(list(it), list(range(3, 10)))
        it = iter(range(10))
        self.assertEqual(list(self.islice(it, 3, 3)), [])
        self.assertEqual(list(it), list(range(3, 10)))
        
        c = count()
        self.assertEqual(list(self.islice(c, 1, 3, 50)), [1])
        self.assertEqual(next(c), 3)


class TestGC(unittest.TestCase):

    def makecycle(self, iterator, container):
        container.append(iterator)
        next(iterator)
        del container, iterator

    def test_accumulate(self):
        a = []
        self.makecycle(accumulate([1,2,a,3]), a)

    def test_batched(self):
        a = []
        self.makecycle(batched([1,2,a,3], 2), a)

    def test_chain(self):
        a = []
        self.makecycle(chain(a), a)

    def test_chain_from_iterable(self):
        a = []
        self.makecycle(chain.from_iterable([a]), a)

    def test_combinations(self):
        a = []
        self.makecycle(combinations([1,2,a,3], 3), a)

    def test_combinations_with_replacement(self):
        a = []
        self.makecycle(combinations_with_replacement([1,2,a,3], 3), a)

    def test_compress(self):
        a = []
        self.makecycle(compress('ABCDEF', [1,0,1,0,1,0]), a)

    def test_count(self):
        a = []
        Int = type('Int', (int,), dict(x=a))
        self.makecycle(count(Int(0), Int(1)), a)

    def test_cycle(self):
        a = []
        self.makecycle(cycle([a]*2), a)

    def test_dropwhile(self):
        a = []
        self.makecycle(dropwhile(bool, [0, a, a]), a)

    def test_groupby(self):
        a = []
        self.makecycle(groupby([a]*2, lambda x:x), a)

    def test_issue2246(self):
        
        n = 10
        keyfunc = lambda x: x
        for i, j in groupby(range(n), key=keyfunc):
            keyfunc.__dict__.setdefault('x',[]).append(j)

    def test_filter(self):
        a = []
        self.makecycle(filter(lambda x:True, [a]*2), a)

    def test_filterfalse(self):
        a = []
        self.makecycle(filterfalse(lambda x:False, a), a)

    def test_zip(self):
        a = []
        self.makecycle(zip([a]*2, [a]*3), a)

    def test_zip_longest(self):
        a = []
        self.makecycle(zip_longest([a]*2, [a]*3), a)
        b = [a, None]
        self.makecycle(zip_longest([a]*2, [a]*3, fillvalue=b), a)

    def test_map(self):
        a = []
        self.makecycle(map(lambda x:x, [a]*2), a)

    def test_islice(self):
        a = []
        self.makecycle(islice([a]*2, None), a)

    def test_pairwise(self):
        a = []
        self.makecycle(pairwise([a]*5), a)

    def test_permutations(self):
        a = []
        self.makecycle(permutations([1,2,a,3], 3), a)

    def test_product(self):
        a = []
        self.makecycle(product([1,2,a,3], repeat=3), a)

    def test_repeat(self):
        a = []
        self.makecycle(repeat(a), a)

    def test_starmap(self):
        a = []
        self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)

    def test_takewhile(self):
        a = []
        self.makecycle(takewhile(bool, [1, 0, a, a]), a)

def R(seqn):
    'Regular generator'
    for i in seqn:
        yield i

class G:
    'Sequence using __getitem__'
    def __init__(self, seqn):
        self.seqn = seqn
    def __getitem__(self, i):
        return self.seqn[i]

class I:
    'Sequence using iterator protocol'
    def __init__(self, seqn):
        self.seqn = seqn
        self.i = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.i >= len(self.seqn): raise StopIteration
        v = self.seqn[self.i]
        self.i += 1
        return v

class Ig:
    'Sequence using iterator protocol defined with a generator'
    def __init__(self, seqn):
        self.seqn = seqn
        self.i = 0
    def __iter__(self):
        for val in self.seqn:
            yield val

class X:
    'Missing __getitem__ and __iter__'
    def __init__(self, seqn):
        self.seqn = seqn
        self.i = 0
    def __next__(self):
        if self.i >= len(self.seqn): raise StopIteration
        v = self.seqn[self.i]
        self.i += 1
        return v

class N:
    'Iterator missing __next__()'
    def __init__(self, seqn):
        self.seqn = seqn
        self.i = 0
    def __iter__(self):
        return self

class E:
    'Test propagation of exceptions'
    def __init__(self, seqn):
        self.seqn = seqn
        self.i = 0
    def __iter__(self):
        return self
    def __next__(self):
        3 // 0

class E2:
    'Test propagation of exceptions after two iterations'
    def __init__(self, seqn):
        self.seqn = seqn
        self.i = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.i == 2:
            raise ZeroDivisionError
        v = self.seqn[self.i]
        self.i += 1
        return v

class S:
    'Test immediate stop'
    def __init__(self, seqn):
        pass
    def __iter__(self):
        return self
    def __next__(self):
        raise StopIteration

def L(seqn):
    'Test multiple tiers of iterators'
    return chain(map(lambda x:x, R(Ig(G(seqn)))))


class TestVariousIteratorArgs(unittest.TestCase):

    def test_accumulate(self):
        s = [1,2,3,4,5]
        r = [1,3,6,10,15]
        n = len(s)
        for g in (G, I, Ig, L, R):
            self.assertEqual(list(accumulate(g(s))), r)
        self.assertEqual(list(accumulate(S(s))), [])
        self.assertRaises(TypeError, accumulate, X(s))
        self.assertRaises(TypeError, accumulate, N(s))
        self.assertRaises(ZeroDivisionError, list, accumulate(E(s)))

    def test_batched(self):
        s = 'abcde'
        r = [('a', 'b'), ('c', 'd'), ('e',)]
        n = 2
        for g in (G, I, Ig, L, R):
            with self.subTest(g=g):
                self.assertEqual(list(batched(g(s), n)), r)
        self.assertEqual(list(batched(S(s), 2)), [])
        self.assertRaises(TypeError, batched, X(s), 2)
        self.assertRaises(TypeError, batched, N(s), 2)
        self.assertRaises(ZeroDivisionError, list, batched(E(s), 2))
        self.assertRaises(ZeroDivisionError, list, batched(E2(s), 4))

    def test_chain(self):
        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
            for g in (G, I, Ig, S, L, R):
                self.assertEqual(list(chain(g(s))), list(g(s)))
                self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
            self.assertRaises(TypeError, list, chain(X(s)))
            self.assertRaises(TypeError, list, chain(N(s)))
            self.assertRaises(ZeroDivisionError, list, chain(E(s)))

    def test_compress(self):
        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
            n = len(s)
            for g in (G, I, Ig, S, L, R):
                self.assertEqual(list(compress(g(s), repeat(1))), list(g(s)))
            self.assertRaises(TypeError, compress, X(s), repeat(1))
            self.assertRaises(TypeError, compress, N(s), repeat(1))
            self.assertRaises(ZeroDivisionError, list, compress(E(s), repeat(1)))

    def test_product(self):
        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
            self.assertRaises(TypeError, product, X(s))
            self.assertRaises(TypeError, product, N(s))
            self.assertRaises(ZeroDivisionError, product, E(s))

    def test_cycle(self):
        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
            for g in (G, I, Ig, S, L, R):
                tgtlen = len(s) * 3
                expected = list(g(s))*3
                actual = list(islice(cycle(g(s)), tgtlen))
                self.assertEqual(actual, expected)
            self.assertRaises(TypeError, cycle, X(s))
            self.assertRaises(TypeError, cycle, N(s))
            self.assertRaises(ZeroDivisionError, list, cycle(E(s)))

    def test_groupby(self):
        for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
            for g in (G, I, Ig, S, L, R):
                self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
            self.assertRaises(TypeError, groupby, X(s))
            self.assertRaises(TypeError, groupby, N(s))
            self.assertRaises(ZeroDivisionError, list, groupby(E(s)))

    def test_filter(self):
        for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
            for g in (G, I, Ig, S, L, R):
                self.assertEqual(list(filter(isEven, g(s))),
                                 [x for x in g(s) if isEven(x)])
            self.assertRaises(TypeError, filter, isEven, X(s))
            self.assertRaises(TypeError, filter, isEven, N(s))
            self.assertRaises(ZeroDivisionError, list, filter(isEven, E(s)))

    def test_filterfalse(self):
        for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
            for g in (G, I, Ig, S, L, R):
                self.assertEqual(list(filterfalse(isEven, g(s))),
                                 [x for x in g(s) if isOdd(x)])
            self.assertRaises(TypeError, filterfalse, isEven, X(s))
            self.assertRaises(TypeError, filterfalse, isEven, N(s))
            self.assertRaises(ZeroDivisionError, list, filterfalse(isEven, E(s)))

    def test_zip(self):
        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
            for g in (G, I, Ig, S, L, R):
                self.assertEqual(list(zip(g(s))), lzip(g(s)))
                self.assertEqual(list(zip(g(s), g(s))), lzip(g(s), g(s)))
            self.assertRaises(TypeError, zip, X(s))
            self.assertRaises(TypeError, zip, N(s))
            self.assertRaises(ZeroDivisionError, list, zip(E(s)))

    def test_ziplongest(self):
        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
            for g in (G, I, Ig, S, L, R):
                self.assertEqual(list(zip_longest(g(s))), list(zip(g(s))))
                self.assertEqual(list(zip_longest(g(s), g(s))), list(zip(g(s), g(s))))
            self.assertRaises(TypeError, zip_longest, X(s))
            self.assertRaises(TypeError, zip_longest, N(s))
            self.assertRaises(ZeroDivisionError, list, zip_longest(E(s)))

    def test_map(self):
        for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
            for g in (G, I, Ig, S, L, R):
                self.assertEqual(list(map(onearg, g(s))),
                                 [onearg(x) for x in g(s)])
                self.assertEqual(list(map(operator.pow, g(s), g(s))),
                                 [x**x for x in g(s)])
            self.assertRaises(TypeError, map, onearg, X(s))
            self.assertRaises(TypeError, map, onearg, N(s))
            self.assertRaises(ZeroDivisionError, list, map(onearg, E(s)))

    def test_islice(self):
        for s in ("12345", "", range(1000), ('do', 1.2), range(2000,2200,5)):
            for g in (G, I, Ig, S, L, R):
                self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
            self.assertRaises(TypeError, islice, X(s), 10)
            self.assertRaises(TypeError, islice, N(s), 10)
            self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))

    def test_pairwise(self):
        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
            for g in (G, I, Ig, S, L, R):
                seq = list(g(s))
                expected = list(zip(seq, seq[1:]))
                actual = list(pairwise(g(s)))
                self.assertEqual(actual, expected)
            self.assertRaises(TypeError, pairwise, X(s))
            self.assertRaises(TypeError, pairwise, N(s))
            self.assertRaises(ZeroDivisionError, list, pairwise(E(s)))

    def test_starmap(self):
        for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
            for g in (G, I, Ig, S, L, R):
                ss = lzip(s, s)
                self.assertEqual(list(starmap(operator.pow, g(ss))),
                                 [x**x for x in g(s)])
            self.assertRaises(TypeError, starmap, operator.pow, X(ss))
            self.assertRaises(TypeError, starmap, operator.pow, N(ss))
            self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))

    def test_takewhile(self):
        for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
            for g in (G, I, Ig, S, L, R):
                tgt = []
                for elem in g(s):
                    if not isEven(elem): break
                    tgt.append(elem)
                self.assertEqual(list(takewhile(isEven, g(s))), tgt)
            self.assertRaises(TypeError, takewhile, isEven, X(s))
            self.assertRaises(TypeError, takewhile, isEven, N(s))
            self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))

    def test_dropwhile(self):
        for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
            for g in (G, I, Ig, S, L, R):
                tgt = []
                for elem in g(s):
                    if not tgt and isOdd(elem): continue
                    tgt.append(elem)
                self.assertEqual(list(dropwhile(isOdd, g(s))), tgt)
            self.assertRaises(TypeError, dropwhile, isOdd, X(s))
            self.assertRaises(TypeError, dropwhile, isOdd, N(s))
            self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))

    def test_tee(self):
        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
            for g in (G, I, Ig, S, L, R):
                it1, it2 = tee(g(s))
                self.assertEqual(list(it1), list(g(s)))
                self.assertEqual(list(it2), list(g(s)))
            self.assertRaises(TypeError, tee, X(s))
            self.assertRaises(TypeError, tee, N(s))
            self.assertRaises(ZeroDivisionError, list, tee(E(s))[0])

class LengthTransparency(unittest.TestCase):

    def test_repeat(self):
        self.assertEqual(operator.length_hint(repeat(None, 50)), 50)
        self.assertEqual(operator.length_hint(repeat(None, 0)), 0)
        self.assertEqual(operator.length_hint(repeat(None), 12), 12)

    def test_repeat_with_negative_times(self):
        self.assertEqual(operator.length_hint(repeat(None, -1)), 0)
        self.assertEqual(operator.length_hint(repeat(None, -2)), 0)
        self.assertEqual(operator.length_hint(repeat(None, times=-1)), 0)
        self.assertEqual(operator.length_hint(repeat(None, times=-2)), 0)

class RegressionTests(unittest.TestCase):

    def test_sf_793826(self):
        

        def mutatingtuple(tuple1, f, tuple2):
            
            
            
            def g(value, first=[1]):
                if first:
                    del first[:]
                    f(next(z))
                return value
            items = list(tuple2)
            items[1:1] = list(tuple1)
            gen = map(g, items)
            z = zip(*[gen]*len(tuple1))
            next(z)

        def f(t):
            global T
            T = t
            first[:] = list(T)

        first = []
        mutatingtuple((1,2,3), f, (4,5,6))
        second = list(T)
        self.assertEqual(first, second)


    def test_sf_950057(self):
        
        

        def gen1():
            hist.append(0)
            yield 1
            hist.append(1)
            raise AssertionError
            hist.append(2)

        def gen2(x):
            hist.append(3)
            yield 2
            hist.append(4)

        hist = []
        self.assertRaises(AssertionError, list, chain(gen1(), gen2(False)))
        self.assertEqual(hist, [0,1])

        hist = []
        self.assertRaises(AssertionError, list, chain(gen1(), gen2(True)))
        self.assertEqual(hist, [0,1])

        hist = []
        self.assertRaises(AssertionError, list, cycle(gen1()))
        self.assertEqual(hist, [0,1])

    @support.skip_if_pgo_task
    @support.requires_resource('cpu')
    def test_long_chain_of_empty_iterables(self):
        
        
        
        it = chain.from_iterable(() for unused in range(10000000))
        with self.assertRaises(StopIteration):
            next(it)

    def test_issue30347_1(self):
        def f(n):
            if n == 5:
                list(b)
            return n != 6
        for (k, b) in groupby(range(10), f):
            list(b)  

    def test_issue30347_2(self):
        class K:
            def __init__(self, v):
                pass
            def __eq__(self, other):
                nonlocal i
                i += 1
                if i == 1:
                    next(g, None)
                return True
        i = 0
        g = next(groupby(range(10), K))[1]
        for j in range(2):
            next(g, None)  


class SubclassWithKwargsTest(unittest.TestCase):
    def test_keywords_in_subclass(self):
        
        testcases = [
            (repeat, (1, 2), [1, 1]),
            (zip, ([1, 2], 'ab'), [(1, 'a'), (2, 'b')]),
            (filter, (None, [0, 1]), [1]),
            (filterfalse, (None, [0, 1]), [0]),
            (chain, ([1, 2], [3, 4]), [1, 2, 3]),
            (map, (str, [1, 2]), ['1', '2']),
            (starmap, (operator.pow, ((2, 3), (3, 2))), [8, 9]),
            (islice, ([1, 2, 3, 4], 1, 3), [2, 3]),
            (takewhile, (isEven, [2, 3, 4]), [2]),
            (dropwhile, (isEven, [2, 3, 4]), [3, 4]),
            (cycle, ([1, 2],), [1, 2, 1]),
            (compress, ('ABC', [1, 0, 1]), ['A', 'C']),
        ]
        for cls, args, result in testcases:
            with self.subTest(cls):
                class subclass(cls):
                    pass
                u = subclass(*args)
                self.assertIs(type(u), subclass)
                self.assertEqual(list(islice(u, 0, 3)), result)
                with self.assertRaises(TypeError):
                    subclass(*args, newarg=3)

        for cls, args, result in testcases:
            
            
            
            if cls in [repeat, zip, compress]:
                continue
            with self.subTest(cls):
                class subclass_with_init(cls):
                    def __init__(self, *args, newarg=None):
                        self.newarg = newarg
                u = subclass_with_init(*args, newarg=3)
                self.assertIs(type(u), subclass_with_init)
                self.assertEqual(list(islice(u, 0, 3)), result)
                self.assertEqual(u.newarg, 3)

        for cls, args, result in testcases:
            with self.subTest(cls):
                class subclass_with_new(cls):
                    def __new__(cls, *args, newarg=None):
                        self = super().__new__(cls, *args)
                        self.newarg = newarg
                        return self
                u = subclass_with_new(*args, newarg=3)
                self.assertIs(type(u), subclass_with_new)
                self.assertEqual(list(islice(u, 0, 3)), result)
                self.assertEqual(u.newarg, 3)


@support.cpython_only
class SizeofTest(unittest.TestCase):
    def setUp(self):
        self.ssize_t = struct.calcsize('n')

    check_sizeof = support.check_sizeof

    def test_product_sizeof(self):
        basesize = support.calcobjsize('3Pi')
        check = self.check_sizeof
        check(product('ab', '12'), basesize + 2 * self.ssize_t)
        check(product(*(('abc',) * 10)), basesize + 10 * self.ssize_t)

    def test_combinations_sizeof(self):
        basesize = support.calcobjsize('3Pni')
        check = self.check_sizeof
        check(combinations('abcd', 3), basesize + 3 * self.ssize_t)
        check(combinations(range(10), 4), basesize + 4 * self.ssize_t)

    def test_combinations_with_replacement_sizeof(self):
        cwr = combinations_with_replacement
        basesize = support.calcobjsize('3Pni')
        check = self.check_sizeof
        check(cwr('abcd', 3), basesize + 3 * self.ssize_t)
        check(cwr(range(10), 4), basesize + 4 * self.ssize_t)

    def test_permutations_sizeof(self):
        basesize = support.calcobjsize('4Pni')
        check = self.check_sizeof
        check(permutations('abcd'),
              basesize + 4 * self.ssize_t + 4 * self.ssize_t)
        check(permutations('abcd', 3),
              basesize + 4 * self.ssize_t + 3 * self.ssize_t)
        check(permutations('abcde', 3),
              basesize + 5 * self.ssize_t + 3 * self.ssize_t)
        check(permutations(range(10), 4),
              basesize + 10 * self.ssize_t + 4 * self.ssize_t)


def load_tests(loader, tests, pattern):
    tests.addTest(doctest.DocTestSuite())
    return tests


if __name__ == "__main__":
    unittest.main()