h SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK J r SSK r \R"\ SL=(a \"\ S5S5"SS\R55r"SS\R5r"S S \R5r"S S \R5r"S S\R5r"SS\R5r"SS\R5r"SS\R5r"SS\R5rSrSrSrSrSrSrSrSr "SS 5r!"S!S"5r"S#r#S$r$S%r%S&r&\\\\\\#\$\%\&S'. r'S(r(\)S):Xa\RT"5 gg!\ a Sr GNGf=f)*N)supportraise_SIGINT_then_send_Nonez+needs _testcapi.raise_SIGINT_then_send_Nonec&\rSrSrSrSrSrSrg)SignalAndYieldFromTestc#># UR5ShvN $N7fN) generator2selfs ;/opt/alt/python313/lib64/python3.13/test/test_generators.py generator1!SignalAndYieldFromTest.generator1s??,,-,s c#6# Sv g![a gf=f7f)NFAILEDPASSED)KeyboardInterruptr s r r !SignalAndYieldFromTest.generator2s%  !    cUR5nURS5 [R"U5 UR [ W5[5 URURS5 g![a nUnSnANMSnAff=f)Nr) rsend _testcapir BaseExceptionassertIstype StopIteration assertEqualvalue)r gen_excexcs r test_raise_and_yield_from0SignalAndYieldFromTest.test_raise_and_yield_from&skoo    1 1# 6 d3i/ H- C sA55 B ?BB N)__name__ __module__ __qualname____firstlineno__rr r"__static_attributes__r$r rrs ..r*rc&\rSrSrSrSrSrSrg)FinalizationTest1c ^U4SjnU"5n[R"U5n[U5 A[R"5 UR U"5S5 UR T5 @[R"5 g)Nc3v># Sv [R"5mg![R"5mf=f7fr )sys _getframe)framesr r2FinalizationTest.test_frame_resurrect..gen5s$ (  s9969)weakrefrefnextr gc_collectr assertTrue)r rgwrr2s @r test_frame_resurrect%FinalizationTest.test_frame_resurrect3s_ ( E [[^ Q  bdD!  r*c~^[RSSnSmU4SjnU"5n[U5 URU5 UR [ R "U5S5 URT5 A[R"5 URT5 UR[RU5 g)NFc32># SvnSv Smg!Smf=f7f)NTr$)r9 finalizeds r r+FinalizationTest.test_refcycle..genJs ! D s) gcgarbager6r assertGreaterr0 getrefcount assertFalserr7r8r)r old_garbagerr9r@s @r test_refcycleFinalizationTest.test_refcycleFsjjm   ! E Q q  3??1-q1 #   " [1r*c^^ SmURT"5[R5 UR[ T"55S5 Sm U 4SjnU 4SjnU4SjnU4SjnTT XX44HznU"5nUR[ U5S5 UR [ 5nURS5 SSS5 URWRRS5 M| g!,(df  N9=f) Nc3# Sv$Nr?r$r$r*r 8FinalizationTest.test_lambda_generator.._s1Wr*r?c3# Sv$7frMr$r$r*r r91FinalizationTest.test_lambda_generator..gcs q!c3*># T"5ShvN $Nr r$r9sr rNrOf nnc3.># T"5ShvN $N7fr r$rTsr g22FinalizationTest.test_lambda_generator..g2gQS.). c3*># T"5ShvN $Nr r$fsr rNrOirUrVc3.># T"5ShvN $N7fr r$r]sr g32FinalizationTest.test_lambda_generator..g3jrZr[rB) assertIsInstancetypes GeneratorTyperr6 assertRaisesrr exceptionr) r f2rXf3r`gen_funrcmr^r9s @@r test_lambda_generator&FinalizationTest.test_lambda_generator\s  ac5#6#67 acA&!&) %)1bb-G)C   T#Y *""=1R 2   R\\// 3 .21s &C++ C9 r$N)r%r&r'r(r;rIrkr)r$r*r r,r,1s&2,4r*r,cJ\rSrSrSrSrSrSrSrSr Sr S r S r S r g ) GeneratorTesttc&SnU"5nURURS5 URURS5 SUlSUlURURS5 URURS5 UR[[ USS5 UR[[ USS5 UR[[ US5 UR[[ US5 S UlS UlU"5nURURS 5 URURS 5 S [S 55nURURS 5 URURS5 g)Nc3# Sv g7frMr$r$r*r func%GeneratorTest.test_name..funcw Grrz%GeneratorTest.test_name..funcnamequalnamer%{r' func_qualname func_namec3$# UHov M g7fr r$.0xs r *GeneratorTest.test_name..s$)Qq) z z*GeneratorTest.test_name..)rr%r're TypeErrorsetattrdelattrrange)r rrrs r test_nameGeneratorTest.test_namevsR f v. ))@ B % v. )):6 )Wc:sC )Wc>3G )Wc:> )Wc>B,# f {3 ))?;%%)$ $ & ))E Gr*cSnU"5nUR[5 [R"U5 SSS5 g!,(df  g=f)Nc3# Sv g7frMr$r$r*r r^"GeneratorTest.test_copy..frtru)rercopyr r^r9s r test_copyGeneratorTest.test_copys3  C   y ) IIaL* ) )s A Ac SnU"5n[[RS-5HGnUR[[R 45 [R "X#5 SSS5 MI g!,(df  M[=f)Nc3# Sv g7frMr$r$r*r r^$GeneratorTest.test_pickle..frtrur?)rpickleHIGHEST_PROTOCOLrer PicklingErrordumps)r r^r9protos r test_pickleGeneratorTest.test_pickles]  C622Q67E""Iv/C/C#DE Q&FE8EEs A33 B cSnU"5nUR[5 URS5 SSS5 UR[ U5S5 g!,(df  N*=f)Nc3# Sv g7frMr$r$r*r r^6GeneratorTest.test_send_non_none_to_new_gen..frtrurr?)rerrrr6rs r test_send_non_none_to_new_gen+GeneratorTest.test_send_non_none_to_new_gensI  C   y ) FF1I* a!$* )s A A$cxSnSn[R"5n[RRU5 [R"SSS5 U"5 [R"U6 [RR 5 "SS5nU"5nU"5UlXUR l[R"SSS5 AU"5 [R"U6 g![R"U6 [RR 5 f=f![R"U6 f=f)Nc.[R"5 gr inspectstack)argss r cb>GeneratorTest.test_handle_frame_object_in_creation..cbs MMOr*c3# Sv g7frMr$r$r*r r?GeneratorTest.test_handle_frame_object_in_creation..genrtrur?rc\rSrSrSrSrg)BGeneratorTest.test_handle_frame_object_in_creation..Sneakyc.[R"5 gr rr s r __del__JGeneratorTest.test_handle_frame_object_in_creation..Sneaky.__del__s  r*r$N)r%r&r'r(rr)r$r*r Sneakyrs r*r)rC get_threshold callbacksappend set_thresholdpop_s)r rr thresholdsrsneakys r $test_handle_frame_object_in_creation2GeneratorTest.test_handle_frame_object_in_creations   %%'  B Aq!  E   j ) LL     H   Aq! * E   j )!   j ) LL      j )sC.D$.3D!$D9cbSnU"5nURURR5 g)Nc# S7v g7fr r$r$r*r r^-GeneratorTest.test_ag_frame_f_back..fs  ) assertIsNoneag_framef_back)r r^ags r test_ag_frame_f_back"GeneratorTest.test_ag_frame_f_back&  S "++,,-r*cSnU"5nURURR5 UR5 g)Nc # g7fr r$r$r*r r^-GeneratorTest.test_cr_frame_f_back..fs s)rcr_framerclose)r r^crs r test_cr_frame_f_back"GeneratorTest.test_cr_frame_f_backs/  S "++,,-  r*cbSnU"5nURURR5 g)Nc3# Sv g7fr r$r$r*r r^-GeneratorTest.test_gi_frame_f_back..f ru)rgi_framer)r r^gis r test_gi_frame_f_back"GeneratorTest.test_gi_frame_f_backrr*c&^SmU4SjnU"5 g)Nc3&# Sv [5e7fr  ValueErrorr$r*r gen_raises2GeneratorTest.test_issue103488..gen_raisess , cR>T"5H nSSLdM g g![a gf=f)NTFr)_rs r loop,GeneratorTest.test_issue103488..loops2 #Au}&  s  &&r$)r rrs @r test_issue103488GeneratorTest.test_issue103488s   r*r$N)r%r&r'r(rrrrrrrrrr)r$r*r rnrnts2"GH'%"*H. . r*rnc ~\rSrSr\"S5\"S5/SQS1Sk\"S5SS S ./r/S QrS rS r Sr Sr Sr Sr g)ModifyUnderlyingIterableTestr)r?rBrB> 0)rB)r?r)N*g@y@c&S[S55$)Nc3$# UHov M g7fr r$r|s r r7ModifyUnderlyingIterableTest.genexpr.. s%9a9rrrr s r genexpr$ModifyUnderlyingIterableTest.genexpr s%59%%r*c*SnU"[S55$)Nc3&# UHnUv M g7fr r$)itr~s r r1ModifyUnderlyingIterableTest.genfunc..gensrrrr rs r genfunc$ModifyUnderlyingIterableTest.genfuncs 59~r*cZURHnU"U5nURX2S9 UR[U5[U55 SSS5 U"[ U55nURXBS9 UR[U5[U55 SSS5 M SnUR H?nU"U5nURUS9 UR [U[U5 SSS5 MA g!,(df  N=f!,(df  GM =f!,(df  Mw=f)N)g_objobj)g_iterrz'.*' object is not iterable)r) iterablessubTestassertListEquallistiter non_iterablesassertRaisesRegexr)r get_generatorrrr err_regexs r process_tests*ModifyUnderlyingIterableTest.process_testss>>C!#&EE3$$T%[$s)<4#49-FV5$$T&\49=65 "2 %%C!#&EE*&&y)T5I+*&4365 +*s#%C74%D D7 D  D  D* cn^^SmUU4SjnUU4SjnTRU5 TRU5 g)Nc6X RRU'U$r )rf_locals)r9localrs r modify_f_localsJModifyUnderlyingIterableTest.test_modify_f_locals..modify_f_locals&s),JJ   &Hr*c4>T"TR5SU5$)Nz.0rrrr s r get_generator_genexprPModifyUnderlyingIterableTest.test_modify_f_locals..get_generator_genexpr*"4<<>4= =r*c4>T"TR5SU5$)Nrrrs r get_generator_genfuncPModifyUnderlyingIterableTest.test_modify_f_locals..get_generator_genfunc-rr*r )r rrrs` @r test_modify_f_locals1ModifyUnderlyingIterableTest.test_modify_f_locals%s2  > > 01 01r*cn^^SmUU4SjnUU4SjnTRU5 TRU5 g)NcT[R"UR05nU"U5$r )rc FunctionTypegi_code)r9rgenerator_funcs r new_gen_from_gi_codeTModifyUnderlyingIterableTest.test_new_gen_from_gi_code..new_gen_from_gi_code4s#"// 2>N!#& &r*c2>T"TR5U5$r rrr$r s r rUModifyUnderlyingIterableTest.test_new_gen_from_gi_code..get_generator_genexpr8' < T"TR5U5$r rr's r rUModifyUnderlyingIterableTest.test_new_gen_from_gi_code..get_generator_genfunc;r)r*r)r rrr$s` @r test_new_gen_from_gi_code6ModifyUnderlyingIterableTest.test_new_gen_from_gi_code3s2 ' = = 01 01r*r$N)r%r&r'r(r frozensetrrrrr rr,r)r$r*r rrsP a b  * ! IM& J 2 2r*rcV\rSrSrSrSrSrSrSrSr Sr S r S r S r S rS rg) ExceptionTestiBc^U4SjnU"5n[U5 [5e![a0nURU5 SnAO![a SnAO f=fSnAff=f[U5 TR [5n[U5 SSS5 O!,(df  O=fTR WR R5 TR [R "55 g)Nc3p># TR[R"55 Sv g![a{nTR [R"5[ 5 TRUR 5 Sv TR [R"5[ 5 Sv eSnAff=f7fr )rr0rf Exceptionrbr __context__r!r s r store_raise_exc_generatorBExceptionTest.test_except_throw..store_raise_exc_generatorGs| !!#--/2 %%cmmozB!!#//2%%cmmozB s%B6(.B6 B3A6B..B33B6) r6rr3throwrerrfr4r0)r r6maker!rjs` r test_except_throwExceptionTest.test_except_throwFs ")* T  ,    3    T   z *b J+ * * ",,223 #--/*s8 % AA AAAAA B B%c^U4SjnU"5n[e![a TR[U5S5 Of=fTR [ R "55 g)Nc3h># TR[R"5[5 Sv g7fNdone)rbr0rfrr sr r+ExceptionTest.test_except_next..genks!  ! !#--/: >Ls/2r?)rr3rr6rr0rfr rr9s` r test_except_nextExceptionTest.test_except_nextjsS  E .  .   T!Wf - . #--/*s %>>c^U4SjnU"5n[U5 [e![a [U5 Of=fTR[U5S5 TR [ R "55 g)Nc3># TR[R"55 Sv [5e![a\nTR [R"5[5 TR [ UR5[5 SnAOSnAff=fTR [R"5[5 Sv TR[R"55 Sv g7fr>) rr0rfrrbrrr4rr5s r r1ExceptionTest.test_except_gen_except..genws D!!#--/2 k! D%%cmmoyA  coo!6 CC D  ! !#--/: >    cmmo .Ls(C627 BABC6BAC6r?)r6rr3rrr0rfrAs` r test_except_gen_except$ExceptionTest.test_except_gen_exceptvsc  E Q    G  a&) #--/*s !99c^^U4SjmU4Sjn[e![a# U"5HnTRUS5 M Of=fTR[R"5S5 g)Nc3># [S5H0nTR[R"5[5 Sv M2 g7f)Nddoing)rrbr0rfr)ir s r r6ExceptionTest.test_nested_gen_except_loop..gens/3Z%%cmmoyA  sAAc3L># [e! T"5HnUv M g=f7fr )r)r~rs r outer8ExceptionTest.test_nested_gen_except_loop..outers'  AGs$ !$rL)rr3rr0rf)r rPr~rs` @r test_nested_gen_except_loop)ExceptionTest.test_nested_gen_except_loops[    -  -W  G, - $/s*AAc^U4SjnU"5n[U5 [e![anURU5 SnAOSnAff=fTR [U5S5 TR [ R"55 g)Nc3`># TR[R"55 Sv TR [R"5[5 Sv TR[R"55 Sv g![a4 TR [R"5[5 [ 5ef=f![ a\nTR [R"5[ 5 TR[UR5[5 SnANSnAff=f7fr>) rr0rfrrbrr3rrr4r5s r r>ExceptionTest.test_except_throw_exception_context..gens D&%%cmmo6  ! !#--/: >    cmmo .L"&))#--/:F#+%& D%%cmmoyA  coo!6 CC Ds;D.(BAD.>CC D+AD&!D.&D++D.r?)r6rr3r8rrr0rf)r rr9r!s` r #test_except_throw_exception_context1ExceptionTest.test_except_throw_exception_contextsj $ E Q    GGCLL  a&) #--/*s! AAAc^^"SS[5nSnU"5nSmTR[T5 URU5 SSS5 TR [ [ U5 UU4SjnU"5n[ U5 TR [ 5 URU5 SSS5 g!,(df  Nr=f!,(df  g=f)Nc\rSrSrSrSrg)8ExceptionTest.test_except_throw_bad_exception..EicU$r r$)clsrkwargss r __new__@ExceptionTest.test_except_throw_bad_exception..E.__new__s r*r$N)r%r&r'r(r_r)r$r*r Er[s r*rac3# Sv g7fr r$r$r*r boring_generatorGExceptionTest.test_except_throw_bad_exception..boring_generatorrruz1should have returned an instance of BaseExceptionc3v># TR[T5 Sv SSS5 g!,(df  g=f7fr )rr)err_msgr sr generator@ExceptionTest.test_except_throw_bad_exception..generators$'' 7;<;;s9( 9 69)r3rrr8rerr6)r rarcrrgrfs` @r test_except_throw_bad_exception-ExceptionTest.test_except_throw_bad_exceptions     E  # #Iw 7 IIaL8 -s3 k S   } - IIaL. -8 7. -sB2C2 C CcSnU"5nUR[5 UR[5 UR [[S5S5 SSS5 SSS5 g!,(df  N=f!,(df  g=f)Nc3# Sv g7f)Nrr$r$r*r r9;ExceptionTest.test_gen_3_arg_deprecation_warning..gs Hru) assertWarnsDeprecationWarningrerr8)r r9rs r "test_gen_3_arg_deprecation_warning0ExceptionTest.test_gen_3_arg_deprecation_warnings^ c   0 1""9- )Yr]D9.2 1--2 1s"A9!A(A9( A6 2A99 BcSnUR[S5 [U"55 SSS5 g!,(df  g=f)Nc3# [e7fr rr$r*r r3ExceptionTest.test_stopiteration_error..gens  rraised StopIteration)r RuntimeErrorr6rs r test_stopiteration_error&ExceptionTest.test_stopiteration_errors0  # #L2H I KJ I Is 4 AcSnU"5nUR[U5S5 UR[S5 [U5 SSS5 g!,(df  g=f)Nc3# Sv [e7frMrur$r*r r^4ExceptionTest.test_tutorial_stopiteration..fsG s r?rw)rr6rrxrs r test_tutorial_stopiteration)ExceptionTest.test_tutorial_stopiterationsI  C a!$  # #L2H I GJ I Is A AcSnU"5nUR[U5S5 UR[5nUR S5 SSS5 URWR R S5 g!,(df  N5=f)Nc3# Sv$7frMr$r$r*r r9*ExceptionTest.test_return_tuple..g G rRr?r)rr6rerrrfrr r9rrjs r test_return_tupleExceptionTest.test_return_tuplesg c cA&   } - HHTN. ++T2. -s A<< B cSnU"5nUR[U5S5 UR[5nUR [S55 SSS5 UR WR R[5 URUR RRS5 g!,(df  Ni=f)Nc3# Sv$7frMr$r$r*r r92ExceptionTest.test_return_stopiteration..grrRr?rB)rr6rerrrbrfrrs r test_return_stopiteration'ExceptionTest.test_return_stopiterations c cA&   } - HH]1% &. bll00-@ ++1115. -s B99 Cr$N)r%r&r'r(r:rBrGrRrWrirqryr~rrr)r$r*r r0r0Bs:"+H ++60(+:4: 3 6r*r0cD\rSrSrSrSrSrSrSrSr Sr S r S r g ) GeneratorCloseTesticxSnU"5nURS5 URUR55 g)Nc3# Sv g7fr r$r$r*r r^8GeneratorCloseTest.test_close_no_return_value..frrurrrr r^rs r test_close_no_return_value-GeneratorCloseTest.test_close_no_return_values/ c  #))+&r*czSnU"5nURS5 URUR5S5 g)Nc36# Sv g![a gf=f7fNr GeneratorExitr$r*r r^5GeneratorCloseTest.test_close_return_value..fs    rr)rrrrs r test_close_return_value*GeneratorCloseTest.test_close_return_values1 c  a(r*cxSnU"5nURS5 URUR55 g)Nc3# Sv g7frr$r$r*r r^:GeneratorCloseTest.test_close_not_catching_exit..f*s rurrs r test_close_not_catching_exit/GeneratorCloseTest.test_close_not_catching_exit)s/  c  #))+&r*cVSnU"5nURUR55 g)Nc36# Sv g![a gf=f7frrr$r*r r^4GeneratorCloseTest.test_close_not_started..f5    r)rrrs r test_close_not_started)GeneratorCloseTest.test_close_not_started4s$  c #))+&r*cSnU"5n[U5 UR[5 [U5 SSS5 URUR 55 g!,(df  N.=f)Nc36# Sv g![a gf=f7frrr$r*r r^2GeneratorCloseTest.test_close_exhausted..f?rr)r6rerrrrs r test_close_exhausted'GeneratorCloseTest.test_close_exhausted>sN  c S   } - I. #))+&. -s A A-cSnU"5nURS5 URUR5S5 URUR55 g)Nc36# Sv g![a gf=f7frrr$r*r r^/GeneratorCloseTest.test_close_closed..fLrrr)rrrrrs r test_close_closed$GeneratorCloseTest.test_close_closedKsE  c  a( #))+&r*cSnU"5nURS5 UR[5 UR5 SSS5 g!,(df  g=f)Nc3J# Sv [e![a [ef=f7fr )rrxr$r*r r^/GeneratorCloseTest.test_close_raises..fXs.  !   s## # #)rrerxrrs r test_close_raises$GeneratorCloseTest.test_close_raisesWs> c    | , IIK- , ,s A  Ac^"SS5nU"5m[R"T5nU4SjnU"5n[U5 @UR5 [R "5 UR U"55 g)Nc\rSrSrSrg)@GeneratorCloseTest.test_close_releases_frame_locals..Fooigr$N)r%r&r'r(r)r$r*r Foorgs r*rc3># TnSv g7fr r$)ar^s r genfnBGeneratorCloseTest.test_close_releases_frame_locals..genfnmsA s )r4r5r6rrr7r)r rf_wrrr9r^s @r test_close_releases_frame_locals3GeneratorCloseTest.test_close_releases_frame_localsds`   E{{1~  G Q    $&!r*r$N) r%r&r'r(rrrrrrrrr)r$r*r rrs*' ) '' ' ' "r*rc2\rSrSrSrSrSrSrSrSr g) GeneratorThrowTestiycHSnU"5nURS5 UR[5nUR[5 SSS5 WRR nUR [U5UR4[S45 g!,(df  NR=f)Nc3J# [S5e![a Sv gf=f7fNrKeyErrorr3r$r*r r^?GeneratorThrowTest.test_exception_context_with_yield..f|s% sm#  s#  # #r rrerr8rfr4rrrr)r r^rrjcontexts r !test_exception_context_with_yield4GeneratorThrowTest.test_exception_context_with_yield{sv  c    z *b IIj !+,,** $w-668JK+ *s B B!c^U4SjnU"5nURS5 UR[5nTRUS5 g)Nc36># [S5e![a| Sv g![agnTR[U5[5 UR nTR[U5UR 4[S45 Sv SnAgSnAff=ff=f7f)Nrrb)rr3rrrr4r)r!rr s r r^PGeneratorThrowTest.test_exception_context_with_yield_inside_generator..fs sm#  $$T#Y ;!ooG$$d7mW\\%B!6*,II  s@B  B!B BAB B B BBBr)rr8rr)r r^ractuals` r 2test_exception_context_with_yield_inside_generatorEGeneratorThrowTest.test_exception_context_with_yield_inside_generators: c :& %r*cV^SmU4SjnU"5nURS5 UR[5nUR[5 SSS5 WRR nUR [U5UR4[S45 g!,(df  NR=f)Nc3# Sv g7fr r$r$r*r r^DGeneratorThrowTest.test_exception_context_with_yield_from..frruc3d># [S5e![a T"5ShvN gf=f7frrr]sr r9DGeneratorThrowTest.test_exception_context_with_yield_from..gs, sm# 3 s 0 -'-0-0rr)r r9rrjrr^s @r &test_exception_context_with_yield_from9GeneratorThrowTest.test_exception_context_with_yield_froms|   c    z *b IIj !+,,** $w-668JK+ *s B B(c^^SmSmUU4Sjn[S5nU"U5nURS5 URU5 URTS5 g)Nc3# Sv g7fr r$r$r*r r^WGeneratorThrowTest.test_exception_context_with_yield_from_with_context_cycle..frruc3># Ue![a9 T"5ShvN O)![anXRLmSnAO SnAff=ff=fSv g7fr )r3r4)r!r^ has_cycles r r9WGeneratorThrowTest.test_exception_context_with_yield_from_with_context_cycle..gsN 9  99 sNN 9!$!7I9 9 sEA A  $$A A AA AAA  ArF)rrr8r)r r9r!rr^rs @@r 9test_exception_context_with_yield_from_with_context_cycleLGeneratorThrowTest.test_exception_context_with_yield_from_with_context_cyclesN   smf  # E*r*cSnU"5nURS5 UR[5nUR[5 SSS5 g!,(df  g=f)Nc3l# [e![a Of=fSv g![a [ef=f7fr )rr3rxr$r*r r9.gs=    # #"" #s(4 44 414)rrerxr8rrs r test_throw_after_none_exc_type1GeneratorThrowTest.test_throw_after_none_exc_typesC #c    | , IIj !- , ,s A Ar$N) r%r&r'r(rrrrrr)r$r*r rrys L&,L"+4"r*rc,\rSrSrSrSrSrSrSrg)GeneratorStackTraceTestic /nU(aiURRnURS5(dURS5(aO&URU5 URnU(aMiUR X25 g)Ncheck_call_)f_codeco_name startswithrrr)r r2expectednamesrvs r check_stack_names)GeneratorStackTraceTest.check_stack_namesse<<''Dx((DOOG,D,D LL LLEe )r*c^^U4SjmUU4SjnU"5nURS5 U"U5 g![a gf=f)Nc3># TR[R"5SS/5 Sv TR[R"5SS/5 g![a N4f=f7f)Nr^r9)rr0r1r3r sr r^;GeneratorStackTraceTest.check_yield_from_example..fsW  " "3==?S#J ?   " "3==?S#J ?  s'(A(A(A( A%"A($A%%A(c3># TR[R"5S/5 T"5ShvN TR[R"5S/5 gN+7f)Nr9)rr0r1)r^r sr r9;GeneratorStackTraceTest.check_yield_from_example..gsD  " "3==?SE :sNN  " "3==?SE : s1A"A ,A")rr)r call_methodr9rr^s` @r check_yield_from_example0GeneratorStackTraceTest.check_yield_from_examplesA @ ; c       s 2 ??c,SnURU5 g)Nc&URS5 gr )rrs r call_sendDGeneratorStackTraceTest.test_send_with_yield_from..call_sends HHTNr*r)r rs r test_send_with_yield_from1GeneratorStackTraceTest.test_send_with_yield_froms  %%i0r*c,SnURU5 g)Nc.UR[5 gr )r8rxrs r call_throwFGeneratorStackTraceTest.test_throw_with_yield_from..call_throws IIl #r*r)r rs r test_throw_with_yield_from2GeneratorStackTraceTest.test_throw_with_yield_froms $ %%j1r*r$N) r%r&r'r(rrrr r)r$r*r rrs **1 2r*rc\rSrSrSrSrg)YieldFromTestsi c"^^^UU4SjmUUU4SjnU"5mTR[R"T5[R5 TR TR 5 TR S5 TR[R"T5[R5 TRTR RRS5 TR S5 TR[R"T5[R5 TR TR 5 TuTR[R"T5[R5 TR TR 5 g)Nc3R># TR[R"T5[R5 TR TR 5 Sv TR[R"T5[R5 TR TR 5 g7fr )rrgetgeneratorstate GEN_RUNNINGr gi_yieldfrom)gen_br sr r5YieldFromTests.test_generator_gi_yieldfrom..ass   W66u=w?R?R S   e00 1    W66u=w?R?R S   e00 1sB$B'c3># TRTR5 T"5ShvN TRTR5 Sv TRTR5 gN?7fr )rr)rrr sr r5YieldFromTests.test_generator_gi_yieldfrom..bsS   e00 1sNN   e00 1    e00 1 s&A+A)AA+r) rrr GEN_CREATEDrrr GEN_SUSPENDEDr"r GEN_CLOSED)r rrrs` @@r test_generator_gi_yieldfrom*YieldFromTests.test_generator_gi_yieldfroms 2 2 22597;N;NO %,,- 4 22597;P;PQ ++33;;SA 4 22597;P;PQ %,,-  22597;M;MN %,,-r*r$N)r%r&r'r(rr)r$r*r r r  s.r*r aL 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 a 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_suspended', '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: attribute 'gi_running' of 'generator' objects is not writable >>> 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#f^^^# S/[T5-mUUU4SjmT"S5HnUv M g7f)Nc3># U[T5:aTv gTU"5HTU'T"US-5HnUv M M g7frMlen)rMr~rgsvaluess r rsimple_conjoin..gensA B<LUWq QqSAG"%sAArr)r r~rr!s` @@r simple_conjoinr#s0Vc"g FVs,1c#^^^^^# [T5mS/T-mUUUUU4SjmUUUU4SjmT"S5HnUv M g7f)Nc3># UT:aTv gTU- S-(a-US-nTU"5HTU'T"U5HnUv M M gT"U5HnUv M g7f)Nrr?r$)rMip1r~_gen3rr nr!s r rconjoin..gensb 6LcQYA#CUWq SAG"% 1XsAAc3@># US-US-US-p2nT XupEnUT :a8U"5H,T U'U"5HT U'U"5H T U'T v M M M. gU"5H;T U'U"5H*T U'U"5HT U'T"U5HnUv M M M, M= g7f)Nr?rBrr$) rMr&ip2ip3r9g1rXr~r'r r(r!s r r'conjoin.._gen3s!QqS!A##qK r !8Sq #%4F3K')ts $ (,$(!Sq #%4F3K')ts !&sA"#G",(,$(!sBBrr)r r~r'rr(r!s` @@@@r conjoinr/sC BAVaZF  $$$*Vs9Ac#B# [U5nS/U-nS/U-n[nSnXQ:a,X"5R=ocU'U"5X%'US- nXQ:aM,Uv US-nUS:aX5"5X%'US- nOgMV!Ua N(f=f!Ua US-nOf=fUS:aM:N)7f)Nrr?)rr__next__)r r(r!iters_StopIterationrMrs r flat_conjoinr4 s BAVaZFVaZE"N A  % " 0 001XD Q%L Q1f !HJ Q 5    " Q  1fsL!B/A9B%B5B9B?BBB BBB Bc&\rSrSrSrSrSrSrg)Queensi/c ^^UTl[U5m/TlTHcnTVs/sH.nSU-SX-U- U-S- --SUSU--S- U-U---PM0 nnU4UU4SjjnTRRU5 Me gs snf)Nr?rBc3># THKnXnUTR-S:XdMT=RU-slUv T=RU)-slMM g7fr)used)rowusesjusesrangenr s r rowgenQueens.__init__..rowgenFsKA":Ddii'1, T)  dU*  s A4A)r(r rowgeneratorsr)r r(rMr;r:r>r=s` @r __init__Queens.__init__0sq A&,-&,QaeAgk!m,.a!A#gai!mAo.0&, - ' + +    % %f --s5Bc#Z# SUl[UR5HnUv M g7fr)r9r/r@)r row2cols r solve Queens.solveQs& t112GM3s)+c URnSSU--n[U5 [U5HPn[U5Vs/sHnSPM nnSXaU'[SSRU5-S-5 [U5 MR gs snf)N+z-+ Q|)r(printrjoin)r rDr(seprMr;squaress r printsolutionQueens.printsolutionVsv FFD1Hn c qA$)!H-HqsHG-"%GAJ  #))C/ 0 #J -s B)r(r@r9N)r%r&r'r(rArErPr)r$r*r r6r6/s.B r*r6c<\rSrSrS SjrSrSrSrSrSr Sr g ) Knightsifct^^^^ ^ ^ TTsTlTl/=m Tl[4U 4Sjjm U 4Sjm U UUU U4SjnU UUU UU 4Sjn[4U U UU 4SjjnTS- S- TS- S- [4U U UU 4SjjnUU 4S jnTT-S :a U/TlgXE/U=(a U=(d U/TT-S - --U/-Tlg) Nc>S=p#TUH;nTUnURU5 U"U5nUS:XaUS- nM.US:XdM6US- nM= US:H=(a US:$)Nrr?rB)remove)i0rne0ne1rMsesuccss r remove_from_successors0Knights.__init__..remove_from_successorsrslMC2Y!H F61HC!V1HC!8'a 'r*cF>TUHnTURU5 M gr )r)rWrMr\s r add_to_successors+Knights.__init__..add_to_successorss!2Ya#r*c3># TS:dTS:agTRSS5nT"U5 UTlUv T"U5 g7f)Nr?r) coords2indexlastij)cornerr`mr(r]r s r firstKnights.__init__..firstsF1uA&&q!,F "6 * DKL f %s# T RSS5nTS:dTS:agSHxupT RX5nT RSU- SU- 5nUT lT"U5 T URU5 UT lUv T UR U5 T"U5 Mz g7f)Nrr)r?rBrBr?)rcfinalrrdrV) rerMr;thisrlr`rfr(r]r r\s r second Knights.__init__..seconds&&q!,F1uA'))!/))!A#qs3" &t,e ##F+"  e ##F+!$''sBB"c3*># /nTTRH,nU"TU5nUS:XaX24/n O&URX245 M. UR5 UH7up2UTR:wdMT"U5(a UTlUv T"U5 M9 g7frM)rdrsortrl)r candidatesrMr[r`r]r r\s r advance!Knights.__init__..advancesJ4;;'aM6#$&J!!1&) (!" ?-a00&' %a( #s A'B.%Br?g@c3x># /nT T RHRnU"T U5nUS:XaUSU4/n OJT RU5upgX`- S-Xq- S--nURXX*U45 MT UR5 UH8upXnUT R:wdMT "U5(a UT lUv T "U5 M: g7f)Nr?rrB)rd index2coordsrrqrl) vmidhmidrrrrMr[i1j1dr`r]r r\s r advance_hard&Knights.__init__..advance_hards J4;;'aM6#$a)J**1-YNbi!^3!!1b!*-(!%a ?-a00&' %a( &s BB:%B:c3*># TRv g7fr )rl)r r\sr lastKnights.__init__..lasts** srr)rfr(r\rsquaregenerators) r rfr(hardrgrnrsr|rr`r]r\s ``` @@@r rAKnights.__init__gsA  ,/ (, $ & & ( (2 ) )4 !sCiqsCiS ) )4  Q37%*GD !%*O&,1'2acAg>%?%D !r*c$XR-U-$r )r()r rMr;s r rcKnights.coords2indexs66zA~r*c,[XR5$r )divmodr()r indexs r rvKnights.index2coordsseVV$$r*c URnUSS2 URURp2URn/SQn[ U5n[ U5HhnUH_nUV V s/sH<upSXy-s=::aU:dMO MSX-s=::aU:dM+O M/U"Xy-X-5PM> n n n UR U 5 Ma Mj gs sn n f)N)rjrk)rB)r?)rr)rr)rr?)rrBr)r\rfr(rcrr) r r\rfr(c2ioffsetsr=rMr;iojorZs r _init_boardKnights._init_boards  !Hvvtvv1;qqA3:77()QT A %(5%()QT A %(5%Sqt_77 Q 7sB< 5B< 9 B< B< B< c#l# UR5 [UR5HnUv M g7fr )rr/r)r r~s r rE Knights.solve s+ ../AG0s24cURURp2[[X#-55nS[U5-S-n[ U5Vs/sH nS/U-PM nnSnUH$nUR U5upXX-XyU 'US- nM& SSU-S-U--n [ U 5 [ U5H2nXvn [ SSRU 5-S-5 [ U 5 M4 gs snf)N%r{r?rH-rK)rfr(rstrrrvrLrM) r r~rfr(wformatrMrOkryrzrNrows r rPKnights.printsolutionsvvtvv1 ACMs1v#',Qx0x!D6A:x0 A&&q)FB$jGKO FA S1Ws]a'' c qA*C # %+ , #J1s C%)rlrdrfr(rr\N)r) r%r&r'r(rArcrvrrErPr)r$r*r rSrSfs"IV % " r*rSae 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 >>> f=lambda: (yield from (1,2)), (yield from (3,4)) Traceback (most recent call last): ... SyntaxError: 'yield from' outside function >>> yield from [1,2] Traceback (most recent call last): ... SyntaxError: 'yield from' outside function >>> 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 here. Maybe you meant '==' instead of '='? >>> 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) >>> import warnings >>> old_filters = warnings.filters.copy() >>> warnings.filterwarnings("ignore", category=DeprecationWarning) # Filter DeprecationWarning: regarding the (type, val, tb) signature of throw(). # Deprecation warnings are re-enabled below. >>> 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 >>> warnings.filters[:] = old_filters # Re-enable DeprecationWarning: the (type, val, tb) exception representation is deprecated, # and may be removed in a future version of Python. 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. ) tutpepemailfunsyntaxr/r4 coroutinerefleakscNUR[R"55 U$r )addTestdoctest DocTestSuite)loadertestspatterns r load_testsr{ s MM'&&() Lr*__main__)+rrCrr0runittestr4rrctestrr ImportError skipUnlesshasattrTestCaserr,rnrr0rrrr tutorial_tests pep_tests email_tests fun_tests syntax_testsr#r/r4r6rS conjoin_tests weakref_testscoroutine_testsrefleaks_tests__test__rr%mainr$r*r rs   Yd*GY(EFBD.X...D.0@4x((@4FCH%%CLE28#4#4E2PN6H%%N6bc"**c"L`"**`"F.2h//.2b.X&&.Bpha  Jz ~i  \o J *0z H00n}}~Q f 0Vp FP'!#!$%%)&   z MMOcSIsE,,E87E8