a ze @sddlZddlZddlZddlZddlZddlZddlZddlmZz ddl Z Wne yfdZ Yn0e e duo|e e ddGdddej ZGdddej ZGd d d ej ZGd d d ej ZGd ddej ZGdddej ZGdddej ZdZdZdZdZdZddZddZddZGdddZGd d!d!Zd"Zd#Z d$Z!d%Z"eeeeeee e!e"d& Z#d+d'd(Z$e%d)kre$d*dS),N)supportraise_SIGINT_then_send_Nonez+needs _testcapi.raise_SIGINT_then_send_Nonec@s$eZdZddZddZddZdS)SignalAndYieldFromTestccs|EdHSN) generator2selfr H/opt/bitninja-python-dojo/embedded/lib/python3.9/test/test_generators.py generator1sz!SignalAndYieldFromTest.generator1ccs(z dVWntyYdS0dSdS)NPASSEDZFAILED)KeyboardInterruptrr r r rs   z!SignalAndYieldFromTest.generator2c Csl|}|dzt|Wn(tyH}z|}WYd}~n d}~00|t|t||j ddS)Nr ) r send _testcapir BaseExceptionassertIstype StopIteration assertEqualvalue)rgenZ_excexcr r r test_raise_and_yield_from$s z0SignalAndYieldFromTest.test_raise_and_yield_fromN)__name__ __module__ __qualname__r rrr r r r rsrc@s$eZdZddZddZddZdS)FinalizationTestcsTfdd}|}t|}t|~t||d|tdS)Nc3s"zdVWtn t0dSr)sys _getframer framer r r3sz2FinalizationTest.test_frame_resurrect..gen)weakrefrefnextr gc_collectr assertTrue)rrgwrr rr test_frame_resurrect1s   z%FinalizationTest.test_frame_resurrectcsxtjdd}dfdd}|}t||||t|d|~t | | tj|dS)NFc3s zdV}dVWdnd0dS)NTr r&Z finalizedr r rHsz+FinalizationTest.test_refcycle..gen) gcZgarbager#rZ assertGreaterr getrefcountZ assertFalserr$r%r)rZ old_garbagerr&r r+r test_refcycleDs    zFinalizationTest.test_refcyclec sddddfdd}fdd}fdd}fd d }||||fD]^}|}|t|d |t}|d Wdn1s0Y||jjd qPdS) NcssdVSNr)r r r r r ]z8FinalizationTest.test_lambda_generator..cssdVSr0r r r r r r&^r2z1FinalizationTest.test_lambda_generator..gc3s EdHSrr r r*r r r1ar2c3s EdHSrr r r*r r g2br2z2FinalizationTest.test_lambda_generator..g2c3s EdHSrr r fr r r1dr2c3s EdHSrr r r4r r g3er2z2FinalizationTest.test_lambda_generator..g3r)r,rr# assertRaisesrr exceptionr)rf2r3Zf3r6Zgen_funrcmr )r5r&r test_lambda_generatorZs     (z&FinalizationTest.test_lambda_generatorN)rrrr(r/r<r r r r r/src@s$eZdZddZddZddZdS) GeneratorTestcCsdd}|}||jd||jdd|_d|_||jd||jd|tt|dd|tt|dd|tt|d|tt|dd |_d |_|}||jd ||jd d d td D}||jd||jd dS)Ncss dVdSr0r r r r r funcrsz%GeneratorTest.test_name..funcr>namequalnamer{rZ func_qualname func_namecss|] }|VqdSrr ).0xr r r r2z*GeneratorTest.test_name.. z )rrrr8 TypeErrorsetattrdelattrrange)rr>rr r r test_nameqs4zGeneratorTest.test_namecCsFdd}|}|tt|Wdn1s80YdS)Ncss dVdSr0r r r r r r5sz"GeneratorTest.test_copy..f)r8rGcopyrr5r&r r r test_copys zGeneratorTest.test_copyc Csbdd}|}ttjdD]@}|ttjft||Wdq1sR0YqdS)Ncss dVdSr0r r r r r r5sz$GeneratorTest.test_pickle..fr))rJpickleHIGHEST_PROTOCOLr8rG PicklingErrordumps)rr5r&protor r r test_pickles zGeneratorTest.test_pickleN)rrrrKrNrTr r r r r=os$r=c@sTeZdZddZddZddZddZd d Zd d Zd dZ ddZ ddZ dS) ExceptionTestc sfdd}|}t|z tWnFtyj}z.z||WntyTYn0WYd}~n d}~00t|t}t|Wdn1s0Y|jjt ddS)Nc 3sztdddVWnfty}zNtdt|jdVtdtdVWYd}~n d}~00dSNr)rrexc_info Exception ValueError assertIsNone __context__rrr r store_raise_exc_generators  zBExceptionTest.test_except_throw..store_raise_exc_generatorNNN) r#rYrXthrowr8rZr9r[rrrW)rr]Zmakerr;r rr test_except_throws    &zExceptionTest.test_except_throwcsRfdd}|}ztWn"ty<t|dYn0tddS)Nc3stdtdVdSNrdone)rrrWrYr rr r rsz+ExceptionTest.test_except_next..genrbr^)rYrXrr#rrWrrr&r rr test_except_nexts  zExceptionTest.test_except_nextcsbfdd}|}t|ztWnty<t|Yn0t|dtddS)Nc 3sz$tdddVtWnJtyn}z2tdtt|jtWYd}~n d}~00tdtdVtddVdSra)rrrWrGrr[rYrZr\rr r rs (z1ExceptionTest.test_except_gen_except..genrbr^)r#rYrXrrrWrcr rr test_except_gen_excepts  z$ExceptionTest.test_except_gen_exceptc svfdd}|}t|ztWn.tyP}z||WYd}~n d}~00t|dtddS)Nc 3szPztdddVWn,tyLtdttYn0WnJty}z2tdtt|jtWYd}~n d}~00tdtdVtddVdSra) rrrWrYrGrXrr[rZr\rr r rs  (z>ExceptionTest.test_except_throw_exception_context..genrbr^)r#rYrXr_rrrW)rrr&rr rr #test_except_throw_exception_contexts  z1ExceptionTest.test_except_throw_exception_contextcsGdddt}dd}|}dt||Wdn1sN0Ytt|fdd}|}t|t||Wdn1s0YdS)Nc@seZdZddZdS)z8ExceptionTest.test_except_throw_bad_exception..Ec_s|Srr )clsargskwargsr r r __new__sz@ExceptionTest.test_except_throw_bad_exception..E.__new__N)rrrrjr r r r Esrkcss dVdSrr r r r r boring_generatorszGExceptionTest.test_except_throw_bad_exception..boring_generatorz1should have returned an instance of BaseExceptionc3s6tdVWdn1s(0YdSr)assertRaisesRegexrGr err_msgrr r generator"sz@ExceptionTest.test_except_throw_bad_exception..generator)rXrmrGr_r8rr#)rrkrlrrpr rnr test_except_throw_bad_exceptions( z-ExceptionTest.test_except_throw_bad_exceptioncCsBdd}|tdt|Wdn1s40YdS)NcsstdVdSrrr r r r r.sz3ExceptionTest.test_stopiteration_error..genraised StopIteration)rm RuntimeErrorr#)rrr r r test_stopiteration_error+sz&ExceptionTest.test_stopiteration_errorcCsVdd}|}|t|d|tdt|Wdn1sH0YdS)NcssdVtdVdS)Nr)r,rrr r r r r58sz4ExceptionTest.test_tutorial_stopiteration..fr)rs)rr#rmrtrMr r r test_tutorial_stopiteration5s z)ExceptionTest.test_tutorial_stopiterationcCsfdd}|}|t|d|t}|dWdn1sH0Y||jjddS)NcssdVSr0r r r r r r&Dsz*ExceptionTest.test_return_tuple..gr))r,r7rr&rr;r r r test_return_tupleCs  (zExceptionTest.test_return_tuplecCs|dd}|}|t|d|t}|tdWdn1sL0Y||jjt||jjjddS)NcssdVSr0r r r r r r&Nsz2ExceptionTest.test_return_stopiteration..gr)r,)rr#r8rrZassertIsInstancer9rrwr r r test_return_stopiterationMs ,z'ExceptionTest.test_return_stopiterationN) rrrr`rdrerfrqrurvrxryr r r r rUs$   rUc@s4eZdZddZddZddZddZd d Zd S) GeneratorThrowTestcCsrdd}|}|d|t}|tWdn1sB0Y|jj}|t||jft dfdS)Ncss*z tdWnty$dVYn0dSNaKeyErrorrXr r r r r5\s  z?GeneratorThrowTest.test_exception_context_with_yield..fr| rr8rYr_r9r[rrrhr~)rr5rr;contextr r r !test_exception_context_with_yield[s  (z4GeneratorThrowTest.test_exception_context_with_yieldcs6fdd}|}|d|t}|ddS)Nc 3sz tdWnxtyz dVWnZty~}zBt|t|j}t||jftdfdVWYd}~n d}~00Yn0dS)Nr|rb)r~rXrrrYr[rh)rrrr r r5ls   zPGeneratorThrowTest.test_exception_context_with_yield_inside_generator..fr)rr_rYr)rr5ractualr rr 2test_exception_context_with_yield_inside_generatoris    zEGeneratorThrowTest.test_exception_context_with_yield_inside_generatorcs~ddfdd}|}|d|t}|tWdn1sN0Y|jj}|t||jft dfdS)Ncss dVdSrr r r r r r5szDGeneratorThrowTest.test_exception_context_with_yield_from..fc3s0z tdWnty*EdHYn0dSr{r}r r4r r r&s  zDGeneratorThrowTest.test_exception_context_with_yield_from..grr)rr&rr;rr r4r &test_exception_context_with_yield_froms   (z9GeneratorThrowTest.test_exception_context_with_yield_fromcsNdddfdd}td}||}|d|||ddS)Ncss dVdSrr r r r r r5szWGeneratorThrowTest.test_exception_context_with_yield_from_with_context_cycle..fc 3sfz|WnRtyZzEdHWn.tyT}z||juWYd}~n d}~00Yn0dVdSr)rXr[r\r5Z has_cycler r r&s &zWGeneratorThrowTest.test_exception_context_with_yield_from_with_context_cycle..gr|F)r~rr_r)rr&rrr rr 9test_exception_context_with_yield_from_with_context_cycles   zLGeneratorThrowTest.test_exception_context_with_yield_from_with_context_cyclecCsPdd}|}|d|t}|tWdn1sB0YdS)NcssBztWntyYn0z dVWnty<tYn0dSr)r~rXrtr r r r r&s   z.g)rr8rtr_rYrwr r r test_throw_after_none_exc_types    z1GeneratorThrowTest.test_throw_after_none_exc_typeN)rrrrrrrrr r r r rzYs rzc@s,eZdZddZddZddZddZd S) GeneratorStackTraceTestcCsHg}|r8|jj}|ds8|dr&q8|||j}q|||dS)NZcheck_Zcall_)f_codeco_name startswithappendf_backr)rr Zexpectednamesr?r r r check_stack_namess z)GeneratorStackTraceTest.check_stack_namescsNfddfdd}|}|dz ||WntyHYn0dS)Nc3sJtddgz dVWnty0Yn0tddgdS)Nr5r&)rrrrXr rr r r5s   z;GeneratorStackTraceTest.check_yield_from_example..fc3s4tdgEdHtdgdS)Nr&)rrrr r5rr r r&s z;GeneratorStackTraceTest.check_yield_from_example..g)rr)rZ call_methodr&rr rr check_yield_from_examples    z0GeneratorStackTraceTest.check_yield_from_examplecCsdd}||dS)NcSs|ddSr)rrr r r call_sendszDGeneratorStackTraceTest.test_send_with_yield_from..call_sendr)rrr r r test_send_with_yield_fromsz1GeneratorStackTraceTest.test_send_with_yield_fromcCsdd}||dS)NcSs|tdSr)r_rtrr r r call_throwszFGeneratorStackTraceTest.test_throw_with_yield_from..call_throwr)rrr r r test_throw_with_yield_fromsz2GeneratorStackTraceTest.test_throw_with_yield_fromN)rrrrrrrr r r r rs rc@seZdZddZdS)YieldFromTestscsfddfdd}|ttjjdttjjjj ddttjj\ttj jdS)Nc3sJttjjdVttjjdSr)rinspectgetgeneratorstateZ GEN_RUNNINGrZ gi_yieldfromr )gen_brr r r|s  z5YieldFromTests.test_generator_gi_yieldfrom..ac3s:jEdHjdVjdSr)rZrr r|rrr r rs    z5YieldFromTests.test_generator_gi_yieldfrom..br|) rrrZ GEN_CREATEDrZrrZ GEN_SUSPENDEDgi_coderZ GEN_CLOSED)rrr rr test_generator_gi_yieldfroms    z*YieldFromTests.test_generator_gi_yieldfromN)rrrrr r r r rsraL Let's try a simple generator: >>> def f(): ... yield 1 ... yield 2 >>> for i in f(): ... print(i) 1 2 >>> g = f() >>> next(g) 1 >>> next(g) 2 "Falling off the end" stops the generator: >>> next(g) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in g StopIteration "return" also stops the generator: >>> def f(): ... yield 1 ... return ... yield 2 # never reached ... >>> g = f() >>> next(g) 1 >>> next(g) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in f StopIteration >>> next(g) # once stopped, can't be resumed Traceback (most recent call last): File "", line 1, in ? StopIteration However, "return" and StopIteration are not exactly equivalent: >>> def g1(): ... try: ... return ... except: ... yield 1 ... >>> list(g1()) [] >>> def g2(): ... try: ... raise StopIteration ... except: ... yield 42 >>> print(list(g2())) [42] This may be surprising at first: >>> def g3(): ... try: ... return ... finally: ... yield 1 ... >>> list(g3()) [1] Let's create an alternate range() function implemented as a generator: >>> def yrange(n): ... for i in range(n): ... yield i ... >>> list(yrange(5)) [0, 1, 2, 3, 4] Generators always return to the most recent caller: >>> def creator(): ... r = yrange(5) ... print("creator", next(r)) ... return r ... >>> def caller(): ... r = creator() ... for i in r: ... print("caller", i) ... >>> caller() creator 0 caller 1 caller 2 caller 3 caller 4 Generators can call other generators: >>> def zrange(n): ... for i in yrange(n): ... yield i ... >>> list(zrange(5)) [0, 1, 2, 3, 4] a Specification: Yield Restriction: A generator cannot be resumed while it is actively running: >>> def g(): ... i = next(me) ... yield i >>> me = g() >>> next(me) Traceback (most recent call last): ... File "", line 2, in g ValueError: generator already executing Specification: Return Note that return isn't always equivalent to raising StopIteration: the difference lies in how enclosing try/except constructs are treated. For example, >>> def f1(): ... try: ... return ... except: ... yield 1 >>> print(list(f1())) [] because, as in any function, return simply exits, but >>> def f2(): ... try: ... raise StopIteration ... except: ... yield 42 >>> print(list(f2())) [42] because StopIteration is captured by a bare "except", as is any exception. Specification: Generators and Exception Propagation >>> def f(): ... return 1//0 >>> def g(): ... yield f() # the zero division exception propagates ... yield 42 # and we'll never get here >>> k = g() >>> next(k) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in g File "", line 2, in f ZeroDivisionError: integer division or modulo by zero >>> next(k) # and the generator cannot be resumed Traceback (most recent call last): File "", line 1, in ? StopIteration >>> Specification: Try/Except/Finally >>> def f(): ... try: ... yield 1 ... try: ... yield 2 ... 1//0 ... yield 3 # never get here ... except ZeroDivisionError: ... yield 4 ... yield 5 ... raise ... except: ... yield 6 ... yield 7 # the "raise" above stops this ... except: ... yield 8 ... yield 9 ... try: ... x = 12 ... finally: ... yield 10 ... yield 11 >>> print(list(f())) [1, 2, 4, 5, 8, 9, 10, 11] >>> Guido's binary tree example. >>> # A binary tree class. >>> class Tree: ... ... def __init__(self, label, left=None, right=None): ... self.label = label ... self.left = left ... self.right = right ... ... def __repr__(self, level=0, indent=" "): ... s = level*indent + repr(self.label) ... if self.left: ... s = s + "\n" + self.left.__repr__(level+1, indent) ... if self.right: ... s = s + "\n" + self.right.__repr__(level+1, indent) ... return s ... ... def __iter__(self): ... return inorder(self) >>> # Create a Tree from a list. >>> def tree(list): ... n = len(list) ... if n == 0: ... return [] ... i = n // 2 ... return Tree(list[i], tree(list[:i]), tree(list[i+1:])) >>> # Show it off: create a tree. >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ") >>> # A recursive generator that generates Tree labels in in-order. >>> def inorder(t): ... if t: ... for x in inorder(t.left): ... yield x ... yield t.label ... for x in inorder(t.right): ... yield x >>> # Show it off: create a tree. >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ") >>> # Print the nodes of the tree in in-order. >>> for x in t: ... print(' '+x, end='') A B C D E F G H I J K L M N O P Q R S T U V W X Y Z >>> # A non-recursive generator. >>> def inorder(node): ... stack = [] ... while node: ... while node.left: ... stack.append(node) ... node = node.left ... yield node.label ... while not node.right: ... try: ... node = stack.pop() ... except IndexError: ... return ... yield node.label ... node = node.right >>> # Exercise the non-recursive generator. >>> for x in t: ... print(' '+x, end='') A B C D E F G H I J K L M N O P Q R S T U V W X Y Z aG The difference between yielding None and returning it. >>> def g(): ... for i in range(3): ... yield None ... yield None ... return >>> list(g()) [None, None, None, None] Ensure that explicitly raising StopIteration acts like any other exception in try/except, not like a return. >>> def g(): ... yield 1 ... try: ... raise StopIteration ... except: ... yield 2 ... yield 3 >>> list(g()) [1, 2, 3] Next one was posted to c.l.py. >>> def gcomb(x, k): ... "Generate all combinations of k elements from list x." ... ... if k > len(x): ... return ... if k == 0: ... yield [] ... else: ... first, rest = x[0], x[1:] ... # A combination does or doesn't contain first. ... # If it does, the remainder is a k-1 comb of rest. ... for c in gcomb(rest, k-1): ... c.insert(0, first) ... yield c ... # If it doesn't contain first, it's a k comb of rest. ... for c in gcomb(rest, k): ... yield c >>> seq = list(range(1, 5)) >>> for k in range(len(seq) + 2): ... print("%d-combs of %s:" % (k, seq)) ... for c in gcomb(seq, k): ... print(" ", c) 0-combs of [1, 2, 3, 4]: [] 1-combs of [1, 2, 3, 4]: [1] [2] [3] [4] 2-combs of [1, 2, 3, 4]: [1, 2] [1, 3] [1, 4] [2, 3] [2, 4] [3, 4] 3-combs of [1, 2, 3, 4]: [1, 2, 3] [1, 2, 4] [1, 3, 4] [2, 3, 4] 4-combs of [1, 2, 3, 4]: [1, 2, 3, 4] 5-combs of [1, 2, 3, 4]: From the Iterators list, about the types of these things. >>> def g(): ... yield 1 ... >>> type(g) >>> i = g() >>> type(i) >>> [s for s in dir(i) if not s.startswith('_')] ['close', 'gi_code', 'gi_frame', 'gi_running', 'gi_yieldfrom', 'send', 'throw'] >>> from test.support import HAVE_DOCSTRINGS >>> print(i.__next__.__doc__ if HAVE_DOCSTRINGS else 'Implement next(self).') Implement next(self). >>> iter(i) is i True >>> import types >>> isinstance(i, types.GeneratorType) True And more, added later. >>> i.gi_running 0 >>> type(i.gi_frame) >>> i.gi_running = 42 Traceback (most recent call last): ... AttributeError: readonly attribute >>> def g(): ... yield me.gi_running >>> me = g() >>> me.gi_running 0 >>> next(me) 1 >>> me.gi_running 0 A clever union-find implementation from c.l.py, due to David Eppstein. Sent: Friday, June 29, 2001 12:16 PM To: python-list@python.org Subject: Re: PEP 255: Simple Generators >>> class disjointSet: ... def __init__(self, name): ... self.name = name ... self.parent = None ... self.generator = self.generate() ... ... def generate(self): ... while not self.parent: ... yield self ... for x in self.parent.generator: ... yield x ... ... def find(self): ... return next(self.generator) ... ... def union(self, parent): ... if self.parent: ... raise ValueError("Sorry, I'm not a root!") ... self.parent = parent ... ... def __str__(self): ... return self.name >>> names = "ABCDEFGHIJKLM" >>> sets = [disjointSet(name) for name in names] >>> roots = sets[:] >>> import random >>> gen = random.Random(42) >>> while 1: ... for s in sets: ... print(" %s->%s" % (s, s.find()), end='') ... print() ... if len(roots) > 1: ... s1 = gen.choice(roots) ... roots.remove(s1) ... s2 = gen.choice(roots) ... s1.union(s2) ... print("merged", s1, "into", s2) ... else: ... break A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M merged K into B A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->B L->L M->M merged A into F A->F B->B C->C D->D E->E F->F G->G H->H I->I J->J K->B L->L M->M merged E into F A->F B->B C->C D->D E->F F->F G->G H->H I->I J->J K->B L->L M->M merged D into C A->F B->B C->C D->C E->F F->F G->G H->H I->I J->J K->B L->L M->M merged M into C A->F B->B C->C D->C E->F F->F G->G H->H I->I J->J K->B L->L M->C merged J into B A->F B->B C->C D->C E->F F->F G->G H->H I->I J->B K->B L->L M->C merged B into C A->F B->C C->C D->C E->F F->F G->G H->H I->I J->C K->C L->L M->C merged F into G A->G B->C C->C D->C E->G F->G G->G H->H I->I J->C K->C L->L M->C merged L into C A->G B->C C->C D->C E->G F->G G->G H->H I->I J->C K->C L->C M->C merged G into I A->I B->C C->C D->C E->I F->I G->I H->H I->I J->C K->C L->C M->C merged I into H A->H B->C C->C D->C E->H F->H G->H H->H I->H J->C K->C L->C M->C merged C into H A->H B->H C->H D->H E->H F->H G->H H->H I->H J->H K->H L->H M->H a Build up to a recursive Sieve of Eratosthenes generator. >>> def firstn(g, n): ... return [next(g) for i in range(n)] >>> def intsfrom(i): ... while 1: ... yield i ... i += 1 >>> firstn(intsfrom(5), 7) [5, 6, 7, 8, 9, 10, 11] >>> def exclude_multiples(n, ints): ... for i in ints: ... if i % n: ... yield i >>> firstn(exclude_multiples(3, intsfrom(1)), 6) [1, 2, 4, 5, 7, 8] >>> def sieve(ints): ... prime = next(ints) ... yield prime ... not_divisible_by_prime = exclude_multiples(prime, ints) ... for p in sieve(not_divisible_by_prime): ... yield p >>> primes = sieve(intsfrom(2)) >>> firstn(primes, 20) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71] Another famous problem: generate all integers of the form 2**i * 3**j * 5**k in increasing order, where i,j,k >= 0. Trickier than it may look at first! Try writing it without generators, and correctly, and without generating 3 internal results for each result output. >>> def times(n, g): ... for i in g: ... yield n * i >>> firstn(times(10, intsfrom(1)), 10) [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] >>> def merge(g, h): ... ng = next(g) ... nh = next(h) ... while 1: ... if ng < nh: ... yield ng ... ng = next(g) ... elif ng > nh: ... yield nh ... nh = next(h) ... else: ... yield ng ... ng = next(g) ... nh = next(h) The following works, but is doing a whale of a lot of redundant work -- it's not clear how to get the internal uses of m235 to share a single generator. Note that me_times2 (etc) each need to see every element in the result sequence. So this is an example where lazy lists are more natural (you can look at the head of a lazy list any number of times). >>> def m235(): ... yield 1 ... me_times2 = times(2, m235()) ... me_times3 = times(3, m235()) ... me_times5 = times(5, m235()) ... for i in merge(merge(me_times2, ... me_times3), ... me_times5): ... yield i Don't print "too many" of these -- the implementation above is extremely inefficient: each call of m235() leads to 3 recursive calls, and in turn each of those 3 more, and so on, and so on, until we've descended enough levels to satisfy the print stmts. Very odd: when I printed 5 lines of results below, this managed to screw up Win98's malloc in "the usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting address space, and it *looked* like a very slow leak. >>> result = m235() >>> for i in range(3): ... print(firstn(result, 15)) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] Heh. Here's one way to get a shared list, complete with an excruciating namespace renaming trick. The *pretty* part is that the times() and merge() functions can be reused as-is, because they only assume their stream arguments are iterable -- a LazyList is the same as a generator to times(). >>> class LazyList: ... def __init__(self, g): ... self.sofar = [] ... self.fetch = g.__next__ ... ... def __getitem__(self, i): ... sofar, fetch = self.sofar, self.fetch ... while i >= len(sofar): ... sofar.append(fetch()) ... return sofar[i] >>> def m235(): ... yield 1 ... # Gack: m235 below actually refers to a LazyList. ... me_times2 = times(2, m235) ... me_times3 = times(3, m235) ... me_times5 = times(5, m235) ... for i in merge(merge(me_times2, ... me_times3), ... me_times5): ... yield i Print as many of these as you like -- *this* implementation is memory- efficient. >>> m235 = LazyList(m235()) >>> for i in range(5): ... print([m235[j] for j in range(15*i, 15*(i+1))]) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] [200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384] [400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675] Ye olde Fibonacci generator, LazyList style. >>> def fibgen(a, b): ... ... def sum(g, h): ... while 1: ... yield next(g) + next(h) ... ... def tail(g): ... next(g) # throw first away ... for x in g: ... yield x ... ... yield a ... yield b ... for s in sum(iter(fib), ... tail(iter(fib))): ... yield s >>> fib = LazyList(fibgen(1, 2)) >>> firstn(iter(fib), 17) [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584] Running after your tail with itertools.tee (new in version 2.4) The algorithms "m235" (Hamming) and Fibonacci presented above are both examples of a whole family of FP (functional programming) algorithms where a function produces and returns a list while the production algorithm suppose the list as already produced by recursively calling itself. For these algorithms to work, they must: - produce at least a first element without presupposing the existence of the rest of the list - produce their elements in a lazy manner To work efficiently, the beginning of the list must not be recomputed over and over again. This is ensured in most FP languages as a built-in feature. In python, we have to explicitly maintain a list of already computed results and abandon genuine recursivity. This is what had been attempted above with the LazyList class. One problem with that class is that it keeps a list of all of the generated results and therefore continually grows. This partially defeats the goal of the generator concept, viz. produce the results only as needed instead of producing them all and thereby wasting memory. Thanks to itertools.tee, it is now clear "how to get the internal uses of m235 to share a single generator". >>> from itertools import tee >>> def m235(): ... def _m235(): ... yield 1 ... for n in merge(times(2, m2), ... merge(times(3, m3), ... times(5, m5))): ... yield n ... m1 = _m235() ... m2, m3, m5, mRes = tee(m1, 4) ... return mRes >>> it = m235() >>> for i in range(5): ... print(firstn(it, 15)) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] [200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384] [400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675] The "tee" function does just what we want. It internally keeps a generated result for as long as it has not been "consumed" from all of the duplicated iterators, whereupon it is deleted. You can therefore print the hamming sequence during hours without increasing memory usage, or very little. The beauty of it is that recursive running-after-their-tail FP algorithms are quite straightforwardly expressed with this Python idiom. Ye olde Fibonacci generator, tee style. >>> def fib(): ... ... def _isum(g, h): ... while 1: ... yield next(g) + next(h) ... ... def _fib(): ... yield 1 ... yield 2 ... next(fibTail) # throw first away ... for res in _isum(fibHead, fibTail): ... yield res ... ... realfib = _fib() ... fibHead, fibTail, fibRes = tee(realfib, 3) ... return fibRes >>> firstn(fib(), 17) [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584] a These are fine: >>> def f(): ... yield 1 ... return >>> def f(): ... try: ... yield 1 ... finally: ... pass >>> def f(): ... try: ... try: ... 1//0 ... except ZeroDivisionError: ... yield 666 ... except: ... pass ... finally: ... pass >>> def f(): ... try: ... try: ... yield 12 ... 1//0 ... except ZeroDivisionError: ... yield 666 ... except: ... try: ... x = 12 ... finally: ... yield 12 ... except: ... return >>> list(f()) [12, 666] >>> def f(): ... yield >>> type(f()) >>> def f(): ... if 0: ... yield >>> type(f()) >>> def f(): ... if 0: ... yield 1 >>> type(f()) >>> def f(): ... if "": ... yield None >>> type(f()) >>> def f(): ... return ... try: ... if x==4: ... pass ... elif 0: ... try: ... 1//0 ... except SyntaxError: ... pass ... else: ... if 0: ... while 12: ... x += 1 ... yield 2 # don't blink ... f(a, b, c, d, e) ... else: ... pass ... except: ... x = 1 ... return >>> type(f()) >>> def f(): ... if 0: ... def g(): ... yield 1 ... >>> type(f()) >>> def f(): ... if 0: ... class C: ... def __init__(self): ... yield 1 ... def f(self): ... yield 2 >>> type(f()) >>> def f(): ... if 0: ... return ... if 0: ... yield 2 >>> type(f()) This one caused a crash (see SF bug 567538): >>> def f(): ... for i in range(3): ... try: ... continue ... finally: ... yield i ... >>> g = f() >>> print(next(g)) 0 >>> print(next(g)) 1 >>> print(next(g)) 2 >>> print(next(g)) Traceback (most recent call last): StopIteration Test the gi_code attribute >>> def f(): ... yield 5 ... >>> g = f() >>> g.gi_code is f.__code__ True >>> next(g) 5 >>> next(g) Traceback (most recent call last): StopIteration >>> g.gi_code is f.__code__ True Test the __name__ attribute and the repr() >>> def f(): ... yield 5 ... >>> g = f() >>> g.__name__ 'f' >>> repr(g) # doctest: +ELLIPSIS '' Lambdas shouldn't have their usual return behavior. >>> x = lambda: (yield 1) >>> list(x()) [1] >>> x = lambda: ((yield 1), (yield 2)) >>> list(x()) [1, 2] c#s6dgtfdddD] }|Vq&dS)Nc3sD|tkrVn,|D] |<|dD] }|Vq2qdSr0len)irDrgsvaluesr r rs  zsimple_conjoin..genrrrrDr rr simple_conjoins rc#sPtdgfddfdddD] }|Vq@dS)Nc3sf|krVnR|drN|d}|D]|<|D] }|Vq>q.n|D] }|VqVdS)Nr)r )rip1rD_gen3rrnrr r rs    zconjoin..genc3s|kr|ddksJ|d|d|d}}}||\}}}|kr|D].|<|D]|<|D]|<VqtqfqXnD|D]<|<|D],|<|D]|<|D] }|VqqqqdS)Nrrr)r,r )rrZip2Zip3r&Zg1r3rD)rrrrr r rs zconjoin.._gen3rrrr rr conjoins   rccst|}dg|}dg|}t}d}z4||krV||j}||<|||<|d7}q&Wn|yjYn0||ksxJ|V|d8}|dkrz||||<|d7}Wq$Wq|y|d8}Yq0q|dksJqq$dS)Nrr))rr__next__)rrrZitersZ_StopIterationritr r r flat_conjoins0       rc@s$eZdZddZddZddZdS)QueenscsT_tg_D]6fddD}|ffdd }j|qdS)NcsHg|]@}d|>d|d>Bddd|>BqSr)r,r rCj)rrr r !s z#Queens.__init__..c3sHD]>}||}|j@dkrj|O_|Vj|M_qdSrV)used)rowusesrZuses)rangenrr r rowgen&s zQueens.__init__..rowgen)rrJ rowgeneratorsr)rrrrr )rrrrr __init__s  zQueens.__init__ccs d|_t|jD] }|VqdSrV)rrr)rrow2colr r r solve1sz Queens.solvecCsx|j}|t|ksJdd|}t|t|D]@}ddt|D}d|||<tdd|dt|q2dS)N+z-+cSsg|]}dqS) r rr r r r<r2z(Queens.printsolution..Q|)rrprintrJjoin)rrrseprsquaresr r r printsolution6s   zQueens.printsolutionN)rrrrrrr r r r rs!rc@s>eZdZdddZddZddZdd Zd d Zd d ZdS)Knightsrc s__g_tffdd fddfdd}fdd}tffd d }d d d d tffd d }fdd}dkr|g_n*||g|r|p|gd|g_dS)Ncsbd}}|D]@}|}||||}|dkr@|d7}q|dkr|d7}q|dko`|dkS)Nrr)r,)remove)i0rZne0Zne1rsesuccsr r remove_from_successorsRs     z0Knights.__init__..remove_from_successorscs |D]}||qdSr)r)rrrr r add_to_successorshs z+Knights.__init__..add_to_successorsc3s@dksdkrdSdd}||_|V|dS)Nr)r) coords2indexlastij)corner)rmrrrr r firstms zKnights.__init__..firstc3sdd}j|ksJdks*dkr.dSt|dksBJdd|vsZJdd|vsrJdD]f\}}||}d|d|}|_||||_|V|||qvdS)Nrrr,r))rr,r))rrrfinalrr)rrrthisrrrrrrrr r secondzs"   z Knights.__init__..secondc3sg}jD]D}||}|dks.Jd|dkrD||fg}q\|||fq||D].\}}|jkr`|r|_|V|q`dS)Nr,else remove_from_successors() pruning flawedr))rrsortr)r candidatesrrrrrrr r advances    z!Knights.__init__..advancer)g@c 3sg}jD]p}||}|dks.Jd|dkrF|d|fg}q|\}}||d||d}||| |fq||D]0\}}}|jkr|r|_|V|qdS)Nrrr)r,)r index2coordsrrr) ZvmidZhmidrrrri1j1drr r advance_hards"   z&Knights.__init__..advance_hardc3s jjvsJjVdSr)rrr )rrr r lastszKnights.__init__..lastr)rrrrsquaregenerators) rrrZhardrrrrrr rr rGs    *  zKnights.__init__cCsFd|kr|jksnJd|kr2|jks8nJ||j|SrV)rr)rrrr r r rszKnights.coords2indexcCs.d|kr|j|jks"nJt||jSrV)rrdivmod)rindexr r r rs"zKnights.index2coordscst|j}|dd=|j|j|jgd}t}tD]2|D](fdd|D}||qDq.)rrrrrJr)rrZoffsetsrrr rr _init_boards  zKnights._init_boardccs"|t|jD] }|VqdSr)rrr)rrDr r r rsz Knights.solvec s|j|j}t||ks"Jtt|}dt|d}fddt|D}d}|D]*}||\}} ||||| <|d7}q`dd|d} t| t|D]*}||} tdd| dt| qdS) N%rcsg|]}dgqSrr )rCrrr r rr2z)Knights.printsolution..r)r-r)rrrstrrJrrr) rrDrwformatrkrrrrrowr rr rs   zKnights.printsolutionN)r) rrrrrrrrrr r r r rFs  rae Generate the 3-bit binary numbers in order. This illustrates dumbest- possible use of conjoin, just to generate the full cross-product. >>> for c in conjoin([lambda: iter((0, 1))] * 3): ... print(c) [0, 0, 0] [0, 0, 1] [0, 1, 0] [0, 1, 1] [1, 0, 0] [1, 0, 1] [1, 1, 0] [1, 1, 1] For efficiency in typical backtracking apps, conjoin() yields the same list object each time. So if you want to save away a full account of its generated sequence, you need to copy its results. >>> def gencopy(iterator): ... for x in iterator: ... yield x[:] >>> for n in range(10): ... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n))) ... print(n, len(all), all[0] == [0] * n, all[-1] == [1] * n) 0 1 True True 1 2 True True 2 4 True True 3 8 True True 4 16 True True 5 32 True True 6 64 True True 7 128 True True 8 256 True True 9 512 True True And run an 8-queens solver. >>> q = Queens(8) >>> LIMIT = 2 >>> count = 0 >>> for row2col in q.solve(): ... count += 1 ... if count <= LIMIT: ... print("Solution", count) ... q.printsolution(row2col) Solution 1 +-+-+-+-+-+-+-+-+ |Q| | | | | | | | +-+-+-+-+-+-+-+-+ | | | | |Q| | | | +-+-+-+-+-+-+-+-+ | | | | | | | |Q| +-+-+-+-+-+-+-+-+ | | | | | |Q| | | +-+-+-+-+-+-+-+-+ | | |Q| | | | | | +-+-+-+-+-+-+-+-+ | | | | | | |Q| | +-+-+-+-+-+-+-+-+ | |Q| | | | | | | +-+-+-+-+-+-+-+-+ | | | |Q| | | | | +-+-+-+-+-+-+-+-+ Solution 2 +-+-+-+-+-+-+-+-+ |Q| | | | | | | | +-+-+-+-+-+-+-+-+ | | | | | |Q| | | +-+-+-+-+-+-+-+-+ | | | | | | | |Q| +-+-+-+-+-+-+-+-+ | | |Q| | | | | | +-+-+-+-+-+-+-+-+ | | | | | | |Q| | +-+-+-+-+-+-+-+-+ | | | |Q| | | | | +-+-+-+-+-+-+-+-+ | |Q| | | | | | | +-+-+-+-+-+-+-+-+ | | | | |Q| | | | +-+-+-+-+-+-+-+-+ >>> print(count, "solutions in all.") 92 solutions in all. And run a Knight's Tour on a 10x10 board. Note that there are about 20,000 solutions even on a 6x6 board, so don't dare run this to exhaustion. >>> k = Knights(10, 10) >>> LIMIT = 2 >>> count = 0 >>> for x in k.solve(): ... count += 1 ... if count <= LIMIT: ... print("Solution", count) ... k.printsolution(x) ... else: ... break Solution 1 +---+---+---+---+---+---+---+---+---+---+ | 1| 58| 27| 34| 3| 40| 29| 10| 5| 8| +---+---+---+---+---+---+---+---+---+---+ | 26| 35| 2| 57| 28| 33| 4| 7| 30| 11| +---+---+---+---+---+---+---+---+---+---+ | 59|100| 73| 36| 41| 56| 39| 32| 9| 6| +---+---+---+---+---+---+---+---+---+---+ | 74| 25| 60| 55| 72| 37| 42| 49| 12| 31| +---+---+---+---+---+---+---+---+---+---+ | 61| 86| 99| 76| 63| 52| 47| 38| 43| 50| +---+---+---+---+---+---+---+---+---+---+ | 24| 75| 62| 85| 54| 71| 64| 51| 48| 13| +---+---+---+---+---+---+---+---+---+---+ | 87| 98| 91| 80| 77| 84| 53| 46| 65| 44| +---+---+---+---+---+---+---+---+---+---+ | 90| 23| 88| 95| 70| 79| 68| 83| 14| 17| +---+---+---+---+---+---+---+---+---+---+ | 97| 92| 21| 78| 81| 94| 19| 16| 45| 66| +---+---+---+---+---+---+---+---+---+---+ | 22| 89| 96| 93| 20| 69| 82| 67| 18| 15| +---+---+---+---+---+---+---+---+---+---+ Solution 2 +---+---+---+---+---+---+---+---+---+---+ | 1| 58| 27| 34| 3| 40| 29| 10| 5| 8| +---+---+---+---+---+---+---+---+---+---+ | 26| 35| 2| 57| 28| 33| 4| 7| 30| 11| +---+---+---+---+---+---+---+---+---+---+ | 59|100| 73| 36| 41| 56| 39| 32| 9| 6| +---+---+---+---+---+---+---+---+---+---+ | 74| 25| 60| 55| 72| 37| 42| 49| 12| 31| +---+---+---+---+---+---+---+---+---+---+ | 61| 86| 99| 76| 63| 52| 47| 38| 43| 50| +---+---+---+---+---+---+---+---+---+---+ | 24| 75| 62| 85| 54| 71| 64| 51| 48| 13| +---+---+---+---+---+---+---+---+---+---+ | 87| 98| 89| 80| 77| 84| 53| 46| 65| 44| +---+---+---+---+---+---+---+---+---+---+ | 90| 23| 92| 95| 70| 79| 68| 83| 14| 17| +---+---+---+---+---+---+---+---+---+---+ | 97| 88| 21| 78| 81| 94| 19| 16| 45| 66| +---+---+---+---+---+---+---+---+---+---+ | 22| 91| 96| 93| 20| 69| 82| 67| 18| 15| +---+---+---+---+---+---+---+---+---+---+ aMGenerators are weakly referencable: >>> import weakref >>> def gen(): ... yield 'foo!' ... >>> wr = weakref.ref(gen) >>> wr() is gen True >>> p = weakref.proxy(gen) Generator-iterators are weakly referencable as well: >>> gi = gen() >>> wr = weakref.ref(gi) >>> wr() is gi True >>> p = weakref.proxy(gi) >>> list(p) ['foo!'] a>>> from test.support import gc_collect Sending a value into a started generator: >>> def f(): ... print((yield 1)) ... yield 2 >>> g = f() >>> next(g) 1 >>> g.send(42) 42 2 Sending a value into a new generator produces a TypeError: >>> f().send("foo") Traceback (most recent call last): ... TypeError: can't send non-None value to a just-started generator Yield by itself yields None: >>> def f(): yield >>> list(f()) [None] Yield is allowed only in the outermost iterable in generator expression: >>> def f(): list(i for i in [(yield 26)]) >>> type(f()) A yield expression with augmented assignment. >>> def coroutine(seq): ... count = 0 ... while count < 200: ... count += yield ... seq.append(count) >>> seq = [] >>> c = coroutine(seq) >>> next(c) >>> print(seq) [] >>> c.send(10) >>> print(seq) [10] >>> c.send(10) >>> print(seq) [10, 20] >>> c.send(10) >>> print(seq) [10, 20, 30] Check some syntax errors for yield expressions: >>> f=lambda: (yield 1),(yield 2) Traceback (most recent call last): ... SyntaxError: 'yield' outside function # Pegen does not produce this error message yet # >>> def f(): x = yield = y # Traceback (most recent call last): # ... # SyntaxError: assignment to yield expression not possible >>> def f(): (yield bar) = y Traceback (most recent call last): ... SyntaxError: cannot assign to yield expression >>> def f(): (yield bar) += y Traceback (most recent call last): ... SyntaxError: 'yield expression' is an illegal expression for augmented assignment Now check some throw() conditions: >>> def f(): ... while True: ... try: ... print((yield)) ... except ValueError as v: ... print("caught ValueError (%s)" % (v)) >>> import sys >>> g = f() >>> next(g) >>> g.throw(ValueError) # type only caught ValueError () >>> g.throw(ValueError("xyz")) # value only caught ValueError (xyz) >>> g.throw(ValueError, ValueError(1)) # value+matching type caught ValueError (1) >>> g.throw(ValueError, TypeError(1)) # mismatched type, rewrapped caught ValueError (1) >>> g.throw(ValueError, ValueError(1), None) # explicit None traceback caught ValueError (1) >>> g.throw(ValueError(1), "foo") # bad args Traceback (most recent call last): ... TypeError: instance exception may not have a separate value >>> g.throw(ValueError, "foo", 23) # bad args Traceback (most recent call last): ... TypeError: throw() third argument must be a traceback object >>> g.throw("abc") Traceback (most recent call last): ... TypeError: exceptions must be classes or instances deriving from BaseException, not str >>> g.throw(0) Traceback (most recent call last): ... TypeError: exceptions must be classes or instances deriving from BaseException, not int >>> g.throw(list) Traceback (most recent call last): ... TypeError: exceptions must be classes or instances deriving from BaseException, not type >>> def throw(g,exc): ... try: ... raise exc ... except: ... g.throw(*sys.exc_info()) >>> throw(g,ValueError) # do it with traceback included caught ValueError () >>> g.send(1) 1 >>> throw(g,TypeError) # terminate the generator Traceback (most recent call last): ... TypeError >>> print(g.gi_frame) None >>> g.send(2) Traceback (most recent call last): ... StopIteration >>> g.throw(ValueError,6) # throw on closed generator Traceback (most recent call last): ... ValueError: 6 >>> f().throw(ValueError,7) # throw on just-opened generator Traceback (most recent call last): ... ValueError: 7 Plain "raise" inside a generator should preserve the traceback (#13188). The traceback should have 3 levels: - g.throw() - f() - 1/0 >>> def f(): ... try: ... yield ... except: ... raise >>> g = f() >>> try: ... 1/0 ... except ZeroDivisionError as v: ... try: ... g.throw(v) ... except Exception as w: ... tb = w.__traceback__ >>> levels = 0 >>> while tb: ... levels += 1 ... tb = tb.tb_next >>> levels 3 Now let's try closing a generator: >>> def f(): ... try: yield ... except GeneratorExit: ... print("exiting") >>> g = f() >>> next(g) >>> g.close() exiting >>> g.close() # should be no-op now >>> f().close() # close on just-opened generator should be fine >>> def f(): yield # an even simpler generator >>> f().close() # close before opening >>> g = f() >>> next(g) >>> g.close() # close normally And finalization: >>> def f(): ... try: yield ... finally: ... print("exiting") >>> g = f() >>> next(g) >>> del g; gc_collect() # For PyPy or other GCs. exiting GeneratorExit is not caught by except Exception: >>> def f(): ... try: yield ... except Exception: ... print('except') ... finally: ... print('finally') >>> g = f() >>> next(g) >>> del g; gc_collect() # For PyPy or other GCs. finally Now let's try some ill-behaved generators: >>> def f(): ... try: yield ... except GeneratorExit: ... yield "foo!" >>> g = f() >>> next(g) >>> g.close() Traceback (most recent call last): ... RuntimeError: generator ignored GeneratorExit >>> g.close() Our ill-behaved code should be invoked during GC: >>> with support.catch_unraisable_exception() as cm: ... g = f() ... next(g) ... del g ... ... cm.unraisable.exc_type == RuntimeError ... "generator ignored GeneratorExit" in str(cm.unraisable.exc_value) ... cm.unraisable.exc_traceback is not None True True True And errors thrown during closing should propagate: >>> def f(): ... try: yield ... except GeneratorExit: ... raise TypeError("fie!") >>> g = f() >>> next(g) >>> g.close() Traceback (most recent call last): ... TypeError: fie! Ensure that various yield expression constructs make their enclosing function a generator: >>> def f(): x += yield >>> type(f()) >>> def f(): x = yield >>> type(f()) >>> def f(): lambda x=(yield): 1 >>> type(f()) >>> def f(d): d[(yield "a")] = d[(yield "b")] = 27 >>> data = [1,2] >>> g = f(data) >>> type(g) >>> g.send(None) 'a' >>> data [1, 2] >>> g.send(0) 'b' >>> data [27, 2] >>> try: g.send(1) ... except StopIteration: pass >>> data [27, 27] ak Prior to adding cycle-GC support to itertools.tee, this code would leak references. We add it to the standard suite so the routine refleak-tests would trigger if it starts being uncleanable again. >>> import itertools >>> def leak(): ... class gen: ... def __iter__(self): ... return self ... def __next__(self): ... return self.item ... g = gen() ... head, tail = itertools.tee(g) ... g.item = head ... return head >>> it = leak() Make sure to also test the involvement of the tee-internal teedataobject, which stores returned items. >>> item = next(it) This test leaked at one point due to generator finalization/destruction. It was copied from Lib/test/leakers/test_generator_cycle.py before the file was removed. >>> def leak(): ... def gen(): ... while True: ... yield g ... g = gen() >>> leak() This test isn't really generator related, but rather exception-in-cleanup related. The coroutine tests (above) just happen to cause an exception in the generator's __del__ (tp_del) method. We can also test for this explicitly, without generators. We do have to redirect stderr to avoid printing warnings and to doublecheck that we actually tested what we wanted to test. >>> from test import support >>> class Leaker: ... def __del__(self): ... def invoke(message): ... raise RuntimeError(message) ... invoke("del failed") ... >>> with support.catch_unraisable_exception() as cm: ... l = Leaker() ... del l ... ... cm.unraisable.object == Leaker.__del__ ... cm.unraisable.exc_type == RuntimeError ... str(cm.unraisable.exc_value) == "del failed" ... cm.unraisable.exc_traceback is not None True True True True These refleak tests should perhaps be in a testfile of their own, test_generators just happened to be the test that drew these out. ) ZtutZpepZemailZfunZsyntaxrr! coroutineZrefleakscCs*ddlm}m}|t|||dS)Nr)rtest_generators)testrrZ run_unittestrZ run_doctest)verboserrr r r test_mainJ s r__main__r))N)&rLr-rOrZunittestr!rrrr ImportErrorZ skipUnlesshasattrZTestCaserrr=rUrzrrZtutorial_testsZ pep_testsZ email_testsZ fun_testsZ syntax_testsrrrrrZ conjoin_testsZ weakref_testsZcoroutine_testsZrefleaks_testsZ__test__rrr r r r st     @65c1!t&@oF=$7@EH