test_generators.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445
  1. import copy
  2. import gc
  3. import pickle
  4. import sys
  5. import doctest
  6. import unittest
  7. import weakref
  8. import inspect
  9. from test import support
  10. try:
  11. import _testcapi
  12. except ImportError:
  13. _testcapi = None
  14. # This tests to make sure that if a SIGINT arrives just before we send into a
  15. # yield from chain, the KeyboardInterrupt is raised in the innermost
  16. # generator (see bpo-30039).
  17. @unittest.skipUnless(_testcapi is not None and
  18. hasattr(_testcapi, "raise_SIGINT_then_send_None"),
  19. "needs _testcapi.raise_SIGINT_then_send_None")
  20. class SignalAndYieldFromTest(unittest.TestCase):
  21. def generator1(self):
  22. return (yield from self.generator2())
  23. def generator2(self):
  24. try:
  25. yield
  26. except KeyboardInterrupt:
  27. return "PASSED"
  28. else:
  29. return "FAILED"
  30. def test_raise_and_yield_from(self):
  31. gen = self.generator1()
  32. gen.send(None)
  33. try:
  34. _testcapi.raise_SIGINT_then_send_None(gen)
  35. except BaseException as _exc:
  36. exc = _exc
  37. self.assertIs(type(exc), StopIteration)
  38. self.assertEqual(exc.value, "PASSED")
  39. class FinalizationTest(unittest.TestCase):
  40. def test_frame_resurrect(self):
  41. # A generator frame can be resurrected by a generator's finalization.
  42. def gen():
  43. nonlocal frame
  44. try:
  45. yield
  46. finally:
  47. frame = sys._getframe()
  48. g = gen()
  49. wr = weakref.ref(g)
  50. next(g)
  51. del g
  52. support.gc_collect()
  53. self.assertIs(wr(), None)
  54. self.assertTrue(frame)
  55. del frame
  56. support.gc_collect()
  57. def test_refcycle(self):
  58. # A generator caught in a refcycle gets finalized anyway.
  59. old_garbage = gc.garbage[:]
  60. finalized = False
  61. def gen():
  62. nonlocal finalized
  63. try:
  64. g = yield
  65. yield 1
  66. finally:
  67. finalized = True
  68. g = gen()
  69. next(g)
  70. g.send(g)
  71. self.assertGreater(sys.getrefcount(g), 2)
  72. self.assertFalse(finalized)
  73. del g
  74. support.gc_collect()
  75. self.assertTrue(finalized)
  76. self.assertEqual(gc.garbage, old_garbage)
  77. def test_lambda_generator(self):
  78. # Issue #23192: Test that a lambda returning a generator behaves
  79. # like the equivalent function
  80. f = lambda: (yield 1)
  81. def g(): return (yield 1)
  82. # test 'yield from'
  83. f2 = lambda: (yield from g())
  84. def g2(): return (yield from g())
  85. f3 = lambda: (yield from f())
  86. def g3(): return (yield from f())
  87. for gen_fun in (f, g, f2, g2, f3, g3):
  88. gen = gen_fun()
  89. self.assertEqual(next(gen), 1)
  90. with self.assertRaises(StopIteration) as cm:
  91. gen.send(2)
  92. self.assertEqual(cm.exception.value, 2)
  93. class GeneratorTest(unittest.TestCase):
  94. def test_name(self):
  95. def func():
  96. yield 1
  97. # check generator names
  98. gen = func()
  99. self.assertEqual(gen.__name__, "func")
  100. self.assertEqual(gen.__qualname__,
  101. "GeneratorTest.test_name.<locals>.func")
  102. # modify generator names
  103. gen.__name__ = "name"
  104. gen.__qualname__ = "qualname"
  105. self.assertEqual(gen.__name__, "name")
  106. self.assertEqual(gen.__qualname__, "qualname")
  107. # generator names must be a string and cannot be deleted
  108. self.assertRaises(TypeError, setattr, gen, '__name__', 123)
  109. self.assertRaises(TypeError, setattr, gen, '__qualname__', 123)
  110. self.assertRaises(TypeError, delattr, gen, '__name__')
  111. self.assertRaises(TypeError, delattr, gen, '__qualname__')
  112. # modify names of the function creating the generator
  113. func.__qualname__ = "func_qualname"
  114. func.__name__ = "func_name"
  115. gen = func()
  116. self.assertEqual(gen.__name__, "func_name")
  117. self.assertEqual(gen.__qualname__, "func_qualname")
  118. # unnamed generator
  119. gen = (x for x in range(10))
  120. self.assertEqual(gen.__name__,
  121. "<genexpr>")
  122. self.assertEqual(gen.__qualname__,
  123. "GeneratorTest.test_name.<locals>.<genexpr>")
  124. def test_copy(self):
  125. def f():
  126. yield 1
  127. g = f()
  128. with self.assertRaises(TypeError):
  129. copy.copy(g)
  130. def test_pickle(self):
  131. def f():
  132. yield 1
  133. g = f()
  134. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  135. with self.assertRaises((TypeError, pickle.PicklingError)):
  136. pickle.dumps(g, proto)
  137. def test_send_non_none_to_new_gen(self):
  138. def f():
  139. yield 1
  140. g = f()
  141. with self.assertRaises(TypeError):
  142. g.send(0)
  143. self.assertEqual(next(g), 1)
  144. def test_handle_frame_object_in_creation(self):
  145. #Attempt to expose partially constructed frames
  146. #See https://github.com/python/cpython/issues/94262
  147. def cb(*args):
  148. inspect.stack()
  149. def gen():
  150. yield 1
  151. thresholds = gc.get_threshold()
  152. gc.callbacks.append(cb)
  153. gc.set_threshold(1, 0, 0)
  154. try:
  155. gen()
  156. finally:
  157. gc.set_threshold(*thresholds)
  158. gc.callbacks.pop()
  159. class Sneaky:
  160. def __del__(self):
  161. inspect.stack()
  162. sneaky = Sneaky()
  163. sneaky._s = Sneaky()
  164. sneaky._s._s = sneaky
  165. gc.set_threshold(1, 0, 0)
  166. try:
  167. del sneaky
  168. gen()
  169. finally:
  170. gc.set_threshold(*thresholds)
  171. def test_ag_frame_f_back(self):
  172. async def f():
  173. yield
  174. ag = f()
  175. self.assertIsNone(ag.ag_frame.f_back)
  176. def test_cr_frame_f_back(self):
  177. async def f():
  178. pass
  179. cr = f()
  180. self.assertIsNone(cr.cr_frame.f_back)
  181. cr.close() # Suppress RuntimeWarning.
  182. def test_gi_frame_f_back(self):
  183. def f():
  184. yield
  185. gi = f()
  186. self.assertIsNone(gi.gi_frame.f_back)
  187. class ExceptionTest(unittest.TestCase):
  188. # Tests for the issue #23353: check that the currently handled exception
  189. # is correctly saved/restored in PyEval_EvalFrameEx().
  190. def test_except_throw(self):
  191. def store_raise_exc_generator():
  192. try:
  193. self.assertEqual(sys.exc_info()[0], None)
  194. yield
  195. except Exception as exc:
  196. # exception raised by gen.throw(exc)
  197. self.assertEqual(sys.exc_info()[0], ValueError)
  198. self.assertIsNone(exc.__context__)
  199. yield
  200. # ensure that the exception is not lost
  201. self.assertEqual(sys.exc_info()[0], ValueError)
  202. yield
  203. # we should be able to raise back the ValueError
  204. raise
  205. make = store_raise_exc_generator()
  206. next(make)
  207. try:
  208. raise ValueError()
  209. except Exception as exc:
  210. try:
  211. make.throw(exc)
  212. except Exception:
  213. pass
  214. next(make)
  215. with self.assertRaises(ValueError) as cm:
  216. next(make)
  217. self.assertIsNone(cm.exception.__context__)
  218. self.assertEqual(sys.exc_info(), (None, None, None))
  219. def test_except_next(self):
  220. def gen():
  221. self.assertEqual(sys.exc_info()[0], ValueError)
  222. yield "done"
  223. g = gen()
  224. try:
  225. raise ValueError
  226. except Exception:
  227. self.assertEqual(next(g), "done")
  228. self.assertEqual(sys.exc_info(), (None, None, None))
  229. def test_except_gen_except(self):
  230. def gen():
  231. try:
  232. self.assertEqual(sys.exc_info()[0], None)
  233. yield
  234. # we are called from "except ValueError:", TypeError must
  235. # inherit ValueError in its context
  236. raise TypeError()
  237. except TypeError as exc:
  238. self.assertEqual(sys.exc_info()[0], TypeError)
  239. self.assertEqual(type(exc.__context__), ValueError)
  240. # here we are still called from the "except ValueError:"
  241. self.assertEqual(sys.exc_info()[0], ValueError)
  242. yield
  243. self.assertIsNone(sys.exc_info()[0])
  244. yield "done"
  245. g = gen()
  246. next(g)
  247. try:
  248. raise ValueError
  249. except Exception:
  250. next(g)
  251. self.assertEqual(next(g), "done")
  252. self.assertEqual(sys.exc_info(), (None, None, None))
  253. def test_except_throw_exception_context(self):
  254. def gen():
  255. try:
  256. try:
  257. self.assertEqual(sys.exc_info()[0], None)
  258. yield
  259. except ValueError:
  260. # we are called from "except ValueError:"
  261. self.assertEqual(sys.exc_info()[0], ValueError)
  262. raise TypeError()
  263. except Exception as exc:
  264. self.assertEqual(sys.exc_info()[0], TypeError)
  265. self.assertEqual(type(exc.__context__), ValueError)
  266. # we are still called from "except ValueError:"
  267. self.assertEqual(sys.exc_info()[0], ValueError)
  268. yield
  269. self.assertIsNone(sys.exc_info()[0])
  270. yield "done"
  271. g = gen()
  272. next(g)
  273. try:
  274. raise ValueError
  275. except Exception as exc:
  276. g.throw(exc)
  277. self.assertEqual(next(g), "done")
  278. self.assertEqual(sys.exc_info(), (None, None, None))
  279. def test_except_throw_bad_exception(self):
  280. class E(Exception):
  281. def __new__(cls, *args, **kwargs):
  282. return cls
  283. def boring_generator():
  284. yield
  285. gen = boring_generator()
  286. err_msg = 'should have returned an instance of BaseException'
  287. with self.assertRaisesRegex(TypeError, err_msg):
  288. gen.throw(E)
  289. self.assertRaises(StopIteration, next, gen)
  290. def generator():
  291. with self.assertRaisesRegex(TypeError, err_msg):
  292. yield
  293. gen = generator()
  294. next(gen)
  295. with self.assertRaises(StopIteration):
  296. gen.throw(E)
  297. def test_stopiteration_error(self):
  298. # See also PEP 479.
  299. def gen():
  300. raise StopIteration
  301. yield
  302. with self.assertRaisesRegex(RuntimeError, 'raised StopIteration'):
  303. next(gen())
  304. def test_tutorial_stopiteration(self):
  305. # Raise StopIteration" stops the generator too:
  306. def f():
  307. yield 1
  308. raise StopIteration
  309. yield 2 # never reached
  310. g = f()
  311. self.assertEqual(next(g), 1)
  312. with self.assertRaisesRegex(RuntimeError, 'raised StopIteration'):
  313. next(g)
  314. def test_return_tuple(self):
  315. def g():
  316. return (yield 1)
  317. gen = g()
  318. self.assertEqual(next(gen), 1)
  319. with self.assertRaises(StopIteration) as cm:
  320. gen.send((2,))
  321. self.assertEqual(cm.exception.value, (2,))
  322. def test_return_stopiteration(self):
  323. def g():
  324. return (yield 1)
  325. gen = g()
  326. self.assertEqual(next(gen), 1)
  327. with self.assertRaises(StopIteration) as cm:
  328. gen.send(StopIteration(2))
  329. self.assertIsInstance(cm.exception.value, StopIteration)
  330. self.assertEqual(cm.exception.value.value, 2)
  331. class GeneratorThrowTest(unittest.TestCase):
  332. def test_exception_context_with_yield(self):
  333. def f():
  334. try:
  335. raise KeyError('a')
  336. except Exception:
  337. yield
  338. gen = f()
  339. gen.send(None)
  340. with self.assertRaises(ValueError) as cm:
  341. gen.throw(ValueError)
  342. context = cm.exception.__context__
  343. self.assertEqual((type(context), context.args), (KeyError, ('a',)))
  344. def test_exception_context_with_yield_inside_generator(self):
  345. # Check that the context is also available from inside the generator
  346. # with yield, as opposed to outside.
  347. def f():
  348. try:
  349. raise KeyError('a')
  350. except Exception:
  351. try:
  352. yield
  353. except Exception as exc:
  354. self.assertEqual(type(exc), ValueError)
  355. context = exc.__context__
  356. self.assertEqual((type(context), context.args),
  357. (KeyError, ('a',)))
  358. yield 'b'
  359. gen = f()
  360. gen.send(None)
  361. actual = gen.throw(ValueError)
  362. # This ensures that the assertions inside were executed.
  363. self.assertEqual(actual, 'b')
  364. def test_exception_context_with_yield_from(self):
  365. def f():
  366. yield
  367. def g():
  368. try:
  369. raise KeyError('a')
  370. except Exception:
  371. yield from f()
  372. gen = g()
  373. gen.send(None)
  374. with self.assertRaises(ValueError) as cm:
  375. gen.throw(ValueError)
  376. context = cm.exception.__context__
  377. self.assertEqual((type(context), context.args), (KeyError, ('a',)))
  378. def test_exception_context_with_yield_from_with_context_cycle(self):
  379. # Check trying to create an exception context cycle:
  380. # https://bugs.python.org/issue40696
  381. has_cycle = None
  382. def f():
  383. yield
  384. def g(exc):
  385. nonlocal has_cycle
  386. try:
  387. raise exc
  388. except Exception:
  389. try:
  390. yield from f()
  391. except Exception as exc:
  392. has_cycle = (exc is exc.__context__)
  393. yield
  394. exc = KeyError('a')
  395. gen = g(exc)
  396. gen.send(None)
  397. gen.throw(exc)
  398. # This also distinguishes from the initial has_cycle=None.
  399. self.assertEqual(has_cycle, False)
  400. def test_throw_after_none_exc_type(self):
  401. def g():
  402. try:
  403. raise KeyError
  404. except KeyError:
  405. pass
  406. try:
  407. yield
  408. except Exception:
  409. raise RuntimeError
  410. gen = g()
  411. gen.send(None)
  412. with self.assertRaises(RuntimeError) as cm:
  413. gen.throw(ValueError)
  414. class GeneratorStackTraceTest(unittest.TestCase):
  415. def check_stack_names(self, frame, expected):
  416. names = []
  417. while frame:
  418. name = frame.f_code.co_name
  419. # Stop checking frames when we get to our test helper.
  420. if name.startswith('check_') or name.startswith('call_'):
  421. break
  422. names.append(name)
  423. frame = frame.f_back
  424. self.assertEqual(names, expected)
  425. def check_yield_from_example(self, call_method):
  426. def f():
  427. self.check_stack_names(sys._getframe(), ['f', 'g'])
  428. try:
  429. yield
  430. except Exception:
  431. pass
  432. self.check_stack_names(sys._getframe(), ['f', 'g'])
  433. def g():
  434. self.check_stack_names(sys._getframe(), ['g'])
  435. yield from f()
  436. self.check_stack_names(sys._getframe(), ['g'])
  437. gen = g()
  438. gen.send(None)
  439. try:
  440. call_method(gen)
  441. except StopIteration:
  442. pass
  443. def test_send_with_yield_from(self):
  444. def call_send(gen):
  445. gen.send(None)
  446. self.check_yield_from_example(call_send)
  447. def test_throw_with_yield_from(self):
  448. def call_throw(gen):
  449. gen.throw(RuntimeError)
  450. self.check_yield_from_example(call_throw)
  451. class YieldFromTests(unittest.TestCase):
  452. def test_generator_gi_yieldfrom(self):
  453. def a():
  454. self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_RUNNING)
  455. self.assertIsNone(gen_b.gi_yieldfrom)
  456. yield
  457. self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_RUNNING)
  458. self.assertIsNone(gen_b.gi_yieldfrom)
  459. def b():
  460. self.assertIsNone(gen_b.gi_yieldfrom)
  461. yield from a()
  462. self.assertIsNone(gen_b.gi_yieldfrom)
  463. yield
  464. self.assertIsNone(gen_b.gi_yieldfrom)
  465. gen_b = b()
  466. self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_CREATED)
  467. self.assertIsNone(gen_b.gi_yieldfrom)
  468. gen_b.send(None)
  469. self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_SUSPENDED)
  470. self.assertEqual(gen_b.gi_yieldfrom.gi_code.co_name, 'a')
  471. gen_b.send(None)
  472. self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_SUSPENDED)
  473. self.assertIsNone(gen_b.gi_yieldfrom)
  474. [] = gen_b # Exhaust generator
  475. self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_CLOSED)
  476. self.assertIsNone(gen_b.gi_yieldfrom)
  477. tutorial_tests = """
  478. Let's try a simple generator:
  479. >>> def f():
  480. ... yield 1
  481. ... yield 2
  482. >>> for i in f():
  483. ... print(i)
  484. 1
  485. 2
  486. >>> g = f()
  487. >>> next(g)
  488. 1
  489. >>> next(g)
  490. 2
  491. "Falling off the end" stops the generator:
  492. >>> next(g)
  493. Traceback (most recent call last):
  494. File "<stdin>", line 1, in ?
  495. File "<stdin>", line 2, in g
  496. StopIteration
  497. "return" also stops the generator:
  498. >>> def f():
  499. ... yield 1
  500. ... return
  501. ... yield 2 # never reached
  502. ...
  503. >>> g = f()
  504. >>> next(g)
  505. 1
  506. >>> next(g)
  507. Traceback (most recent call last):
  508. File "<stdin>", line 1, in ?
  509. File "<stdin>", line 3, in f
  510. StopIteration
  511. >>> next(g) # once stopped, can't be resumed
  512. Traceback (most recent call last):
  513. File "<stdin>", line 1, in ?
  514. StopIteration
  515. However, "return" and StopIteration are not exactly equivalent:
  516. >>> def g1():
  517. ... try:
  518. ... return
  519. ... except:
  520. ... yield 1
  521. ...
  522. >>> list(g1())
  523. []
  524. >>> def g2():
  525. ... try:
  526. ... raise StopIteration
  527. ... except:
  528. ... yield 42
  529. >>> print(list(g2()))
  530. [42]
  531. This may be surprising at first:
  532. >>> def g3():
  533. ... try:
  534. ... return
  535. ... finally:
  536. ... yield 1
  537. ...
  538. >>> list(g3())
  539. [1]
  540. Let's create an alternate range() function implemented as a generator:
  541. >>> def yrange(n):
  542. ... for i in range(n):
  543. ... yield i
  544. ...
  545. >>> list(yrange(5))
  546. [0, 1, 2, 3, 4]
  547. Generators always return to the most recent caller:
  548. >>> def creator():
  549. ... r = yrange(5)
  550. ... print("creator", next(r))
  551. ... return r
  552. ...
  553. >>> def caller():
  554. ... r = creator()
  555. ... for i in r:
  556. ... print("caller", i)
  557. ...
  558. >>> caller()
  559. creator 0
  560. caller 1
  561. caller 2
  562. caller 3
  563. caller 4
  564. Generators can call other generators:
  565. >>> def zrange(n):
  566. ... for i in yrange(n):
  567. ... yield i
  568. ...
  569. >>> list(zrange(5))
  570. [0, 1, 2, 3, 4]
  571. """
  572. # The examples from PEP 255.
  573. pep_tests = """
  574. Specification: Yield
  575. Restriction: A generator cannot be resumed while it is actively
  576. running:
  577. >>> def g():
  578. ... i = next(me)
  579. ... yield i
  580. >>> me = g()
  581. >>> next(me)
  582. Traceback (most recent call last):
  583. ...
  584. File "<string>", line 2, in g
  585. ValueError: generator already executing
  586. Specification: Return
  587. Note that return isn't always equivalent to raising StopIteration: the
  588. difference lies in how enclosing try/except constructs are treated.
  589. For example,
  590. >>> def f1():
  591. ... try:
  592. ... return
  593. ... except:
  594. ... yield 1
  595. >>> print(list(f1()))
  596. []
  597. because, as in any function, return simply exits, but
  598. >>> def f2():
  599. ... try:
  600. ... raise StopIteration
  601. ... except:
  602. ... yield 42
  603. >>> print(list(f2()))
  604. [42]
  605. because StopIteration is captured by a bare "except", as is any
  606. exception.
  607. Specification: Generators and Exception Propagation
  608. >>> def f():
  609. ... return 1//0
  610. >>> def g():
  611. ... yield f() # the zero division exception propagates
  612. ... yield 42 # and we'll never get here
  613. >>> k = g()
  614. >>> next(k)
  615. Traceback (most recent call last):
  616. File "<stdin>", line 1, in ?
  617. File "<stdin>", line 2, in g
  618. File "<stdin>", line 2, in f
  619. ZeroDivisionError: integer division or modulo by zero
  620. >>> next(k) # and the generator cannot be resumed
  621. Traceback (most recent call last):
  622. File "<stdin>", line 1, in ?
  623. StopIteration
  624. >>>
  625. Specification: Try/Except/Finally
  626. >>> def f():
  627. ... try:
  628. ... yield 1
  629. ... try:
  630. ... yield 2
  631. ... 1//0
  632. ... yield 3 # never get here
  633. ... except ZeroDivisionError:
  634. ... yield 4
  635. ... yield 5
  636. ... raise
  637. ... except:
  638. ... yield 6
  639. ... yield 7 # the "raise" above stops this
  640. ... except:
  641. ... yield 8
  642. ... yield 9
  643. ... try:
  644. ... x = 12
  645. ... finally:
  646. ... yield 10
  647. ... yield 11
  648. >>> print(list(f()))
  649. [1, 2, 4, 5, 8, 9, 10, 11]
  650. >>>
  651. Guido's binary tree example.
  652. >>> # A binary tree class.
  653. >>> class Tree:
  654. ...
  655. ... def __init__(self, label, left=None, right=None):
  656. ... self.label = label
  657. ... self.left = left
  658. ... self.right = right
  659. ...
  660. ... def __repr__(self, level=0, indent=" "):
  661. ... s = level*indent + repr(self.label)
  662. ... if self.left:
  663. ... s = s + "\\n" + self.left.__repr__(level+1, indent)
  664. ... if self.right:
  665. ... s = s + "\\n" + self.right.__repr__(level+1, indent)
  666. ... return s
  667. ...
  668. ... def __iter__(self):
  669. ... return inorder(self)
  670. >>> # Create a Tree from a list.
  671. >>> def tree(list):
  672. ... n = len(list)
  673. ... if n == 0:
  674. ... return []
  675. ... i = n // 2
  676. ... return Tree(list[i], tree(list[:i]), tree(list[i+1:]))
  677. >>> # Show it off: create a tree.
  678. >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
  679. >>> # A recursive generator that generates Tree labels in in-order.
  680. >>> def inorder(t):
  681. ... if t:
  682. ... for x in inorder(t.left):
  683. ... yield x
  684. ... yield t.label
  685. ... for x in inorder(t.right):
  686. ... yield x
  687. >>> # Show it off: create a tree.
  688. >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
  689. >>> # Print the nodes of the tree in in-order.
  690. >>> for x in t:
  691. ... print(' '+x, end='')
  692. 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
  693. >>> # A non-recursive generator.
  694. >>> def inorder(node):
  695. ... stack = []
  696. ... while node:
  697. ... while node.left:
  698. ... stack.append(node)
  699. ... node = node.left
  700. ... yield node.label
  701. ... while not node.right:
  702. ... try:
  703. ... node = stack.pop()
  704. ... except IndexError:
  705. ... return
  706. ... yield node.label
  707. ... node = node.right
  708. >>> # Exercise the non-recursive generator.
  709. >>> for x in t:
  710. ... print(' '+x, end='')
  711. 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
  712. """
  713. # Examples from Iterator-List and Python-Dev and c.l.py.
  714. email_tests = """
  715. The difference between yielding None and returning it.
  716. >>> def g():
  717. ... for i in range(3):
  718. ... yield None
  719. ... yield None
  720. ... return
  721. >>> list(g())
  722. [None, None, None, None]
  723. Ensure that explicitly raising StopIteration acts like any other exception
  724. in try/except, not like a return.
  725. >>> def g():
  726. ... yield 1
  727. ... try:
  728. ... raise StopIteration
  729. ... except:
  730. ... yield 2
  731. ... yield 3
  732. >>> list(g())
  733. [1, 2, 3]
  734. Next one was posted to c.l.py.
  735. >>> def gcomb(x, k):
  736. ... "Generate all combinations of k elements from list x."
  737. ...
  738. ... if k > len(x):
  739. ... return
  740. ... if k == 0:
  741. ... yield []
  742. ... else:
  743. ... first, rest = x[0], x[1:]
  744. ... # A combination does or doesn't contain first.
  745. ... # If it does, the remainder is a k-1 comb of rest.
  746. ... for c in gcomb(rest, k-1):
  747. ... c.insert(0, first)
  748. ... yield c
  749. ... # If it doesn't contain first, it's a k comb of rest.
  750. ... for c in gcomb(rest, k):
  751. ... yield c
  752. >>> seq = list(range(1, 5))
  753. >>> for k in range(len(seq) + 2):
  754. ... print("%d-combs of %s:" % (k, seq))
  755. ... for c in gcomb(seq, k):
  756. ... print(" ", c)
  757. 0-combs of [1, 2, 3, 4]:
  758. []
  759. 1-combs of [1, 2, 3, 4]:
  760. [1]
  761. [2]
  762. [3]
  763. [4]
  764. 2-combs of [1, 2, 3, 4]:
  765. [1, 2]
  766. [1, 3]
  767. [1, 4]
  768. [2, 3]
  769. [2, 4]
  770. [3, 4]
  771. 3-combs of [1, 2, 3, 4]:
  772. [1, 2, 3]
  773. [1, 2, 4]
  774. [1, 3, 4]
  775. [2, 3, 4]
  776. 4-combs of [1, 2, 3, 4]:
  777. [1, 2, 3, 4]
  778. 5-combs of [1, 2, 3, 4]:
  779. From the Iterators list, about the types of these things.
  780. >>> def g():
  781. ... yield 1
  782. ...
  783. >>> type(g)
  784. <class 'function'>
  785. >>> i = g()
  786. >>> type(i)
  787. <class 'generator'>
  788. >>> [s for s in dir(i) if not s.startswith('_')]
  789. ['close', 'gi_code', 'gi_frame', 'gi_running', 'gi_suspended', 'gi_yieldfrom', 'send', 'throw']
  790. >>> from test.support import HAVE_DOCSTRINGS
  791. >>> print(i.__next__.__doc__ if HAVE_DOCSTRINGS else 'Implement next(self).')
  792. Implement next(self).
  793. >>> iter(i) is i
  794. True
  795. >>> import types
  796. >>> isinstance(i, types.GeneratorType)
  797. True
  798. And more, added later.
  799. >>> i.gi_running
  800. 0
  801. >>> type(i.gi_frame)
  802. <class 'frame'>
  803. >>> i.gi_running = 42
  804. Traceback (most recent call last):
  805. ...
  806. AttributeError: attribute 'gi_running' of 'generator' objects is not writable
  807. >>> def g():
  808. ... yield me.gi_running
  809. >>> me = g()
  810. >>> me.gi_running
  811. 0
  812. >>> next(me)
  813. 1
  814. >>> me.gi_running
  815. 0
  816. A clever union-find implementation from c.l.py, due to David Eppstein.
  817. Sent: Friday, June 29, 2001 12:16 PM
  818. To: python-list@python.org
  819. Subject: Re: PEP 255: Simple Generators
  820. >>> class disjointSet:
  821. ... def __init__(self, name):
  822. ... self.name = name
  823. ... self.parent = None
  824. ... self.generator = self.generate()
  825. ...
  826. ... def generate(self):
  827. ... while not self.parent:
  828. ... yield self
  829. ... for x in self.parent.generator:
  830. ... yield x
  831. ...
  832. ... def find(self):
  833. ... return next(self.generator)
  834. ...
  835. ... def union(self, parent):
  836. ... if self.parent:
  837. ... raise ValueError("Sorry, I'm not a root!")
  838. ... self.parent = parent
  839. ...
  840. ... def __str__(self):
  841. ... return self.name
  842. >>> names = "ABCDEFGHIJKLM"
  843. >>> sets = [disjointSet(name) for name in names]
  844. >>> roots = sets[:]
  845. >>> import random
  846. >>> gen = random.Random(42)
  847. >>> while 1:
  848. ... for s in sets:
  849. ... print(" %s->%s" % (s, s.find()), end='')
  850. ... print()
  851. ... if len(roots) > 1:
  852. ... s1 = gen.choice(roots)
  853. ... roots.remove(s1)
  854. ... s2 = gen.choice(roots)
  855. ... s1.union(s2)
  856. ... print("merged", s1, "into", s2)
  857. ... else:
  858. ... break
  859. 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
  860. merged K into B
  861. 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
  862. merged A into F
  863. 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
  864. merged E into F
  865. 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
  866. merged D into C
  867. 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
  868. merged M into C
  869. 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
  870. merged J into B
  871. 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
  872. merged B into C
  873. 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
  874. merged F into G
  875. 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
  876. merged L into C
  877. 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
  878. merged G into I
  879. 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
  880. merged I into H
  881. 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
  882. merged C into H
  883. 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
  884. """
  885. # Emacs turd '
  886. # Fun tests (for sufficiently warped notions of "fun").
  887. fun_tests = """
  888. Build up to a recursive Sieve of Eratosthenes generator.
  889. >>> def firstn(g, n):
  890. ... return [next(g) for i in range(n)]
  891. >>> def intsfrom(i):
  892. ... while 1:
  893. ... yield i
  894. ... i += 1
  895. >>> firstn(intsfrom(5), 7)
  896. [5, 6, 7, 8, 9, 10, 11]
  897. >>> def exclude_multiples(n, ints):
  898. ... for i in ints:
  899. ... if i % n:
  900. ... yield i
  901. >>> firstn(exclude_multiples(3, intsfrom(1)), 6)
  902. [1, 2, 4, 5, 7, 8]
  903. >>> def sieve(ints):
  904. ... prime = next(ints)
  905. ... yield prime
  906. ... not_divisible_by_prime = exclude_multiples(prime, ints)
  907. ... for p in sieve(not_divisible_by_prime):
  908. ... yield p
  909. >>> primes = sieve(intsfrom(2))
  910. >>> firstn(primes, 20)
  911. [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
  912. Another famous problem: generate all integers of the form
  913. 2**i * 3**j * 5**k
  914. in increasing order, where i,j,k >= 0. Trickier than it may look at first!
  915. Try writing it without generators, and correctly, and without generating
  916. 3 internal results for each result output.
  917. >>> def times(n, g):
  918. ... for i in g:
  919. ... yield n * i
  920. >>> firstn(times(10, intsfrom(1)), 10)
  921. [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
  922. >>> def merge(g, h):
  923. ... ng = next(g)
  924. ... nh = next(h)
  925. ... while 1:
  926. ... if ng < nh:
  927. ... yield ng
  928. ... ng = next(g)
  929. ... elif ng > nh:
  930. ... yield nh
  931. ... nh = next(h)
  932. ... else:
  933. ... yield ng
  934. ... ng = next(g)
  935. ... nh = next(h)
  936. The following works, but is doing a whale of a lot of redundant work --
  937. it's not clear how to get the internal uses of m235 to share a single
  938. generator. Note that me_times2 (etc) each need to see every element in the
  939. result sequence. So this is an example where lazy lists are more natural
  940. (you can look at the head of a lazy list any number of times).
  941. >>> def m235():
  942. ... yield 1
  943. ... me_times2 = times(2, m235())
  944. ... me_times3 = times(3, m235())
  945. ... me_times5 = times(5, m235())
  946. ... for i in merge(merge(me_times2,
  947. ... me_times3),
  948. ... me_times5):
  949. ... yield i
  950. Don't print "too many" of these -- the implementation above is extremely
  951. inefficient: each call of m235() leads to 3 recursive calls, and in
  952. turn each of those 3 more, and so on, and so on, until we've descended
  953. enough levels to satisfy the print stmts. Very odd: when I printed 5
  954. lines of results below, this managed to screw up Win98's malloc in "the
  955. usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting
  956. address space, and it *looked* like a very slow leak.
  957. >>> result = m235()
  958. >>> for i in range(3):
  959. ... print(firstn(result, 15))
  960. [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
  961. [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
  962. [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
  963. Heh. Here's one way to get a shared list, complete with an excruciating
  964. namespace renaming trick. The *pretty* part is that the times() and merge()
  965. functions can be reused as-is, because they only assume their stream
  966. arguments are iterable -- a LazyList is the same as a generator to times().
  967. >>> class LazyList:
  968. ... def __init__(self, g):
  969. ... self.sofar = []
  970. ... self.fetch = g.__next__
  971. ...
  972. ... def __getitem__(self, i):
  973. ... sofar, fetch = self.sofar, self.fetch
  974. ... while i >= len(sofar):
  975. ... sofar.append(fetch())
  976. ... return sofar[i]
  977. >>> def m235():
  978. ... yield 1
  979. ... # Gack: m235 below actually refers to a LazyList.
  980. ... me_times2 = times(2, m235)
  981. ... me_times3 = times(3, m235)
  982. ... me_times5 = times(5, m235)
  983. ... for i in merge(merge(me_times2,
  984. ... me_times3),
  985. ... me_times5):
  986. ... yield i
  987. Print as many of these as you like -- *this* implementation is memory-
  988. efficient.
  989. >>> m235 = LazyList(m235())
  990. >>> for i in range(5):
  991. ... print([m235[j] for j in range(15*i, 15*(i+1))])
  992. [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
  993. [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
  994. [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
  995. [200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
  996. [400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
  997. Ye olde Fibonacci generator, LazyList style.
  998. >>> def fibgen(a, b):
  999. ...
  1000. ... def sum(g, h):
  1001. ... while 1:
  1002. ... yield next(g) + next(h)
  1003. ...
  1004. ... def tail(g):
  1005. ... next(g) # throw first away
  1006. ... for x in g:
  1007. ... yield x
  1008. ...
  1009. ... yield a
  1010. ... yield b
  1011. ... for s in sum(iter(fib),
  1012. ... tail(iter(fib))):
  1013. ... yield s
  1014. >>> fib = LazyList(fibgen(1, 2))
  1015. >>> firstn(iter(fib), 17)
  1016. [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
  1017. Running after your tail with itertools.tee (new in version 2.4)
  1018. The algorithms "m235" (Hamming) and Fibonacci presented above are both
  1019. examples of a whole family of FP (functional programming) algorithms
  1020. where a function produces and returns a list while the production algorithm
  1021. suppose the list as already produced by recursively calling itself.
  1022. For these algorithms to work, they must:
  1023. - produce at least a first element without presupposing the existence of
  1024. the rest of the list
  1025. - produce their elements in a lazy manner
  1026. To work efficiently, the beginning of the list must not be recomputed over
  1027. and over again. This is ensured in most FP languages as a built-in feature.
  1028. In python, we have to explicitly maintain a list of already computed results
  1029. and abandon genuine recursivity.
  1030. This is what had been attempted above with the LazyList class. One problem
  1031. with that class is that it keeps a list of all of the generated results and
  1032. therefore continually grows. This partially defeats the goal of the generator
  1033. concept, viz. produce the results only as needed instead of producing them
  1034. all and thereby wasting memory.
  1035. Thanks to itertools.tee, it is now clear "how to get the internal uses of
  1036. m235 to share a single generator".
  1037. >>> from itertools import tee
  1038. >>> def m235():
  1039. ... def _m235():
  1040. ... yield 1
  1041. ... for n in merge(times(2, m2),
  1042. ... merge(times(3, m3),
  1043. ... times(5, m5))):
  1044. ... yield n
  1045. ... m1 = _m235()
  1046. ... m2, m3, m5, mRes = tee(m1, 4)
  1047. ... return mRes
  1048. >>> it = m235()
  1049. >>> for i in range(5):
  1050. ... print(firstn(it, 15))
  1051. [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
  1052. [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
  1053. [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
  1054. [200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
  1055. [400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
  1056. The "tee" function does just what we want. It internally keeps a generated
  1057. result for as long as it has not been "consumed" from all of the duplicated
  1058. iterators, whereupon it is deleted. You can therefore print the hamming
  1059. sequence during hours without increasing memory usage, or very little.
  1060. The beauty of it is that recursive running-after-their-tail FP algorithms
  1061. are quite straightforwardly expressed with this Python idiom.
  1062. Ye olde Fibonacci generator, tee style.
  1063. >>> def fib():
  1064. ...
  1065. ... def _isum(g, h):
  1066. ... while 1:
  1067. ... yield next(g) + next(h)
  1068. ...
  1069. ... def _fib():
  1070. ... yield 1
  1071. ... yield 2
  1072. ... next(fibTail) # throw first away
  1073. ... for res in _isum(fibHead, fibTail):
  1074. ... yield res
  1075. ...
  1076. ... realfib = _fib()
  1077. ... fibHead, fibTail, fibRes = tee(realfib, 3)
  1078. ... return fibRes
  1079. >>> firstn(fib(), 17)
  1080. [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
  1081. """
  1082. # syntax_tests mostly provokes SyntaxErrors. Also fiddling with #if 0
  1083. # hackery.
  1084. syntax_tests = """
  1085. These are fine:
  1086. >>> def f():
  1087. ... yield 1
  1088. ... return
  1089. >>> def f():
  1090. ... try:
  1091. ... yield 1
  1092. ... finally:
  1093. ... pass
  1094. >>> def f():
  1095. ... try:
  1096. ... try:
  1097. ... 1//0
  1098. ... except ZeroDivisionError:
  1099. ... yield 666
  1100. ... except:
  1101. ... pass
  1102. ... finally:
  1103. ... pass
  1104. >>> def f():
  1105. ... try:
  1106. ... try:
  1107. ... yield 12
  1108. ... 1//0
  1109. ... except ZeroDivisionError:
  1110. ... yield 666
  1111. ... except:
  1112. ... try:
  1113. ... x = 12
  1114. ... finally:
  1115. ... yield 12
  1116. ... except:
  1117. ... return
  1118. >>> list(f())
  1119. [12, 666]
  1120. >>> def f():
  1121. ... yield
  1122. >>> type(f())
  1123. <class 'generator'>
  1124. >>> def f():
  1125. ... if 0:
  1126. ... yield
  1127. >>> type(f())
  1128. <class 'generator'>
  1129. >>> def f():
  1130. ... if 0:
  1131. ... yield 1
  1132. >>> type(f())
  1133. <class 'generator'>
  1134. >>> def f():
  1135. ... if "":
  1136. ... yield None
  1137. >>> type(f())
  1138. <class 'generator'>
  1139. >>> def f():
  1140. ... return
  1141. ... try:
  1142. ... if x==4:
  1143. ... pass
  1144. ... elif 0:
  1145. ... try:
  1146. ... 1//0
  1147. ... except SyntaxError:
  1148. ... pass
  1149. ... else:
  1150. ... if 0:
  1151. ... while 12:
  1152. ... x += 1
  1153. ... yield 2 # don't blink
  1154. ... f(a, b, c, d, e)
  1155. ... else:
  1156. ... pass
  1157. ... except:
  1158. ... x = 1
  1159. ... return
  1160. >>> type(f())
  1161. <class 'generator'>
  1162. >>> def f():
  1163. ... if 0:
  1164. ... def g():
  1165. ... yield 1
  1166. ...
  1167. >>> type(f())
  1168. <class 'NoneType'>
  1169. >>> def f():
  1170. ... if 0:
  1171. ... class C:
  1172. ... def __init__(self):
  1173. ... yield 1
  1174. ... def f(self):
  1175. ... yield 2
  1176. >>> type(f())
  1177. <class 'NoneType'>
  1178. >>> def f():
  1179. ... if 0:
  1180. ... return
  1181. ... if 0:
  1182. ... yield 2
  1183. >>> type(f())
  1184. <class 'generator'>
  1185. This one caused a crash (see SF bug 567538):
  1186. >>> def f():
  1187. ... for i in range(3):
  1188. ... try:
  1189. ... continue
  1190. ... finally:
  1191. ... yield i
  1192. ...
  1193. >>> g = f()
  1194. >>> print(next(g))
  1195. 0
  1196. >>> print(next(g))
  1197. 1
  1198. >>> print(next(g))
  1199. 2
  1200. >>> print(next(g))
  1201. Traceback (most recent call last):
  1202. StopIteration
  1203. Test the gi_code attribute
  1204. >>> def f():
  1205. ... yield 5
  1206. ...
  1207. >>> g = f()
  1208. >>> g.gi_code is f.__code__
  1209. True
  1210. >>> next(g)
  1211. 5
  1212. >>> next(g)
  1213. Traceback (most recent call last):
  1214. StopIteration
  1215. >>> g.gi_code is f.__code__
  1216. True
  1217. Test the __name__ attribute and the repr()
  1218. >>> def f():
  1219. ... yield 5
  1220. ...
  1221. >>> g = f()
  1222. >>> g.__name__
  1223. 'f'
  1224. >>> repr(g) # doctest: +ELLIPSIS
  1225. '<generator object f at ...>'
  1226. Lambdas shouldn't have their usual return behavior.
  1227. >>> x = lambda: (yield 1)
  1228. >>> list(x())
  1229. [1]
  1230. >>> x = lambda: ((yield 1), (yield 2))
  1231. >>> list(x())
  1232. [1, 2]
  1233. """
  1234. # conjoin is a simple backtracking generator, named in honor of Icon's
  1235. # "conjunction" control structure. Pass a list of no-argument functions
  1236. # that return iterable objects. Easiest to explain by example: assume the
  1237. # function list [x, y, z] is passed. Then conjoin acts like:
  1238. #
  1239. # def g():
  1240. # values = [None] * 3
  1241. # for values[0] in x():
  1242. # for values[1] in y():
  1243. # for values[2] in z():
  1244. # yield values
  1245. #
  1246. # So some 3-lists of values *may* be generated, each time we successfully
  1247. # get into the innermost loop. If an iterator fails (is exhausted) before
  1248. # then, it "backtracks" to get the next value from the nearest enclosing
  1249. # iterator (the one "to the left"), and starts all over again at the next
  1250. # slot (pumps a fresh iterator). Of course this is most useful when the
  1251. # iterators have side-effects, so that which values *can* be generated at
  1252. # each slot depend on the values iterated at previous slots.
  1253. def simple_conjoin(gs):
  1254. values = [None] * len(gs)
  1255. def gen(i):
  1256. if i >= len(gs):
  1257. yield values
  1258. else:
  1259. for values[i] in gs[i]():
  1260. for x in gen(i+1):
  1261. yield x
  1262. for x in gen(0):
  1263. yield x
  1264. # That works fine, but recursing a level and checking i against len(gs) for
  1265. # each item produced is inefficient. By doing manual loop unrolling across
  1266. # generator boundaries, it's possible to eliminate most of that overhead.
  1267. # This isn't worth the bother *in general* for generators, but conjoin() is
  1268. # a core building block for some CPU-intensive generator applications.
  1269. def conjoin(gs):
  1270. n = len(gs)
  1271. values = [None] * n
  1272. # Do one loop nest at time recursively, until the # of loop nests
  1273. # remaining is divisible by 3.
  1274. def gen(i):
  1275. if i >= n:
  1276. yield values
  1277. elif (n-i) % 3:
  1278. ip1 = i+1
  1279. for values[i] in gs[i]():
  1280. for x in gen(ip1):
  1281. yield x
  1282. else:
  1283. for x in _gen3(i):
  1284. yield x
  1285. # Do three loop nests at a time, recursing only if at least three more
  1286. # remain. Don't call directly: this is an internal optimization for
  1287. # gen's use.
  1288. def _gen3(i):
  1289. assert i < n and (n-i) % 3 == 0
  1290. ip1, ip2, ip3 = i+1, i+2, i+3
  1291. g, g1, g2 = gs[i : ip3]
  1292. if ip3 >= n:
  1293. # These are the last three, so we can yield values directly.
  1294. for values[i] in g():
  1295. for values[ip1] in g1():
  1296. for values[ip2] in g2():
  1297. yield values
  1298. else:
  1299. # At least 6 loop nests remain; peel off 3 and recurse for the
  1300. # rest.
  1301. for values[i] in g():
  1302. for values[ip1] in g1():
  1303. for values[ip2] in g2():
  1304. for x in _gen3(ip3):
  1305. yield x
  1306. for x in gen(0):
  1307. yield x
  1308. # And one more approach: For backtracking apps like the Knight's Tour
  1309. # solver below, the number of backtracking levels can be enormous (one
  1310. # level per square, for the Knight's Tour, so that e.g. a 100x100 board
  1311. # needs 10,000 levels). In such cases Python is likely to run out of
  1312. # stack space due to recursion. So here's a recursion-free version of
  1313. # conjoin too.
  1314. # NOTE WELL: This allows large problems to be solved with only trivial
  1315. # demands on stack space. Without explicitly resumable generators, this is
  1316. # much harder to achieve. OTOH, this is much slower (up to a factor of 2)
  1317. # than the fancy unrolled recursive conjoin.
  1318. def flat_conjoin(gs): # rename to conjoin to run tests with this instead
  1319. n = len(gs)
  1320. values = [None] * n
  1321. iters = [None] * n
  1322. _StopIteration = StopIteration # make local because caught a *lot*
  1323. i = 0
  1324. while 1:
  1325. # Descend.
  1326. try:
  1327. while i < n:
  1328. it = iters[i] = gs[i]().__next__
  1329. values[i] = it()
  1330. i += 1
  1331. except _StopIteration:
  1332. pass
  1333. else:
  1334. assert i == n
  1335. yield values
  1336. # Backtrack until an older iterator can be resumed.
  1337. i -= 1
  1338. while i >= 0:
  1339. try:
  1340. values[i] = iters[i]()
  1341. # Success! Start fresh at next level.
  1342. i += 1
  1343. break
  1344. except _StopIteration:
  1345. # Continue backtracking.
  1346. i -= 1
  1347. else:
  1348. assert i < 0
  1349. break
  1350. # A conjoin-based N-Queens solver.
  1351. class Queens:
  1352. def __init__(self, n):
  1353. self.n = n
  1354. rangen = range(n)
  1355. # Assign a unique int to each column and diagonal.
  1356. # columns: n of those, range(n).
  1357. # NW-SE diagonals: 2n-1 of these, i-j unique and invariant along
  1358. # each, smallest i-j is 0-(n-1) = 1-n, so add n-1 to shift to 0-
  1359. # based.
  1360. # NE-SW diagonals: 2n-1 of these, i+j unique and invariant along
  1361. # each, smallest i+j is 0, largest is 2n-2.
  1362. # For each square, compute a bit vector of the columns and
  1363. # diagonals it covers, and for each row compute a function that
  1364. # generates the possibilities for the columns in that row.
  1365. self.rowgenerators = []
  1366. for i in rangen:
  1367. rowuses = [(1 << j) | # column ordinal
  1368. (1 << (n + i-j + n-1)) | # NW-SE ordinal
  1369. (1 << (n + 2*n-1 + i+j)) # NE-SW ordinal
  1370. for j in rangen]
  1371. def rowgen(rowuses=rowuses):
  1372. for j in rangen:
  1373. uses = rowuses[j]
  1374. if uses & self.used == 0:
  1375. self.used |= uses
  1376. yield j
  1377. self.used &= ~uses
  1378. self.rowgenerators.append(rowgen)
  1379. # Generate solutions.
  1380. def solve(self):
  1381. self.used = 0
  1382. for row2col in conjoin(self.rowgenerators):
  1383. yield row2col
  1384. def printsolution(self, row2col):
  1385. n = self.n
  1386. assert n == len(row2col)
  1387. sep = "+" + "-+" * n
  1388. print(sep)
  1389. for i in range(n):
  1390. squares = [" " for j in range(n)]
  1391. squares[row2col[i]] = "Q"
  1392. print("|" + "|".join(squares) + "|")
  1393. print(sep)
  1394. # A conjoin-based Knight's Tour solver. This is pretty sophisticated
  1395. # (e.g., when used with flat_conjoin above, and passing hard=1 to the
  1396. # constructor, a 200x200 Knight's Tour was found quickly -- note that we're
  1397. # creating 10s of thousands of generators then!), and is lengthy.
  1398. class Knights:
  1399. def __init__(self, m, n, hard=0):
  1400. self.m, self.n = m, n
  1401. # solve() will set up succs[i] to be a list of square #i's
  1402. # successors.
  1403. succs = self.succs = []
  1404. # Remove i0 from each of its successor's successor lists, i.e.
  1405. # successors can't go back to i0 again. Return 0 if we can
  1406. # detect this makes a solution impossible, else return 1.
  1407. def remove_from_successors(i0, len=len):
  1408. # If we remove all exits from a free square, we're dead:
  1409. # even if we move to it next, we can't leave it again.
  1410. # If we create a square with one exit, we must visit it next;
  1411. # else somebody else will have to visit it, and since there's
  1412. # only one adjacent, there won't be a way to leave it again.
  1413. # Finally, if we create more than one free square with a
  1414. # single exit, we can only move to one of them next, leaving
  1415. # the other one a dead end.
  1416. ne0 = ne1 = 0
  1417. for i in succs[i0]:
  1418. s = succs[i]
  1419. s.remove(i0)
  1420. e = len(s)
  1421. if e == 0:
  1422. ne0 += 1
  1423. elif e == 1:
  1424. ne1 += 1
  1425. return ne0 == 0 and ne1 < 2
  1426. # Put i0 back in each of its successor's successor lists.
  1427. def add_to_successors(i0):
  1428. for i in succs[i0]:
  1429. succs[i].append(i0)
  1430. # Generate the first move.
  1431. def first():
  1432. if m < 1 or n < 1:
  1433. return
  1434. # Since we're looking for a cycle, it doesn't matter where we
  1435. # start. Starting in a corner makes the 2nd move easy.
  1436. corner = self.coords2index(0, 0)
  1437. remove_from_successors(corner)
  1438. self.lastij = corner
  1439. yield corner
  1440. add_to_successors(corner)
  1441. # Generate the second moves.
  1442. def second():
  1443. corner = self.coords2index(0, 0)
  1444. assert self.lastij == corner # i.e., we started in the corner
  1445. if m < 3 or n < 3:
  1446. return
  1447. assert len(succs[corner]) == 2
  1448. assert self.coords2index(1, 2) in succs[corner]
  1449. assert self.coords2index(2, 1) in succs[corner]
  1450. # Only two choices. Whichever we pick, the other must be the
  1451. # square picked on move m*n, as it's the only way to get back
  1452. # to (0, 0). Save its index in self.final so that moves before
  1453. # the last know it must be kept free.
  1454. for i, j in (1, 2), (2, 1):
  1455. this = self.coords2index(i, j)
  1456. final = self.coords2index(3-i, 3-j)
  1457. self.final = final
  1458. remove_from_successors(this)
  1459. succs[final].append(corner)
  1460. self.lastij = this
  1461. yield this
  1462. succs[final].remove(corner)
  1463. add_to_successors(this)
  1464. # Generate moves 3 through m*n-1.
  1465. def advance(len=len):
  1466. # If some successor has only one exit, must take it.
  1467. # Else favor successors with fewer exits.
  1468. candidates = []
  1469. for i in succs[self.lastij]:
  1470. e = len(succs[i])
  1471. assert e > 0, "else remove_from_successors() pruning flawed"
  1472. if e == 1:
  1473. candidates = [(e, i)]
  1474. break
  1475. candidates.append((e, i))
  1476. else:
  1477. candidates.sort()
  1478. for e, i in candidates:
  1479. if i != self.final:
  1480. if remove_from_successors(i):
  1481. self.lastij = i
  1482. yield i
  1483. add_to_successors(i)
  1484. # Generate moves 3 through m*n-1. Alternative version using a
  1485. # stronger (but more expensive) heuristic to order successors.
  1486. # Since the # of backtracking levels is m*n, a poor move early on
  1487. # can take eons to undo. Smallest square board for which this
  1488. # matters a lot is 52x52.
  1489. def advance_hard(vmid=(m-1)/2.0, hmid=(n-1)/2.0, len=len):
  1490. # If some successor has only one exit, must take it.
  1491. # Else favor successors with fewer exits.
  1492. # Break ties via max distance from board centerpoint (favor
  1493. # corners and edges whenever possible).
  1494. candidates = []
  1495. for i in succs[self.lastij]:
  1496. e = len(succs[i])
  1497. assert e > 0, "else remove_from_successors() pruning flawed"
  1498. if e == 1:
  1499. candidates = [(e, 0, i)]
  1500. break
  1501. i1, j1 = self.index2coords(i)
  1502. d = (i1 - vmid)**2 + (j1 - hmid)**2
  1503. candidates.append((e, -d, i))
  1504. else:
  1505. candidates.sort()
  1506. for e, d, i in candidates:
  1507. if i != self.final:
  1508. if remove_from_successors(i):
  1509. self.lastij = i
  1510. yield i
  1511. add_to_successors(i)
  1512. # Generate the last move.
  1513. def last():
  1514. assert self.final in succs[self.lastij]
  1515. yield self.final
  1516. if m*n < 4:
  1517. self.squaregenerators = [first]
  1518. else:
  1519. self.squaregenerators = [first, second] + \
  1520. [hard and advance_hard or advance] * (m*n - 3) + \
  1521. [last]
  1522. def coords2index(self, i, j):
  1523. assert 0 <= i < self.m
  1524. assert 0 <= j < self.n
  1525. return i * self.n + j
  1526. def index2coords(self, index):
  1527. assert 0 <= index < self.m * self.n
  1528. return divmod(index, self.n)
  1529. def _init_board(self):
  1530. succs = self.succs
  1531. del succs[:]
  1532. m, n = self.m, self.n
  1533. c2i = self.coords2index
  1534. offsets = [( 1, 2), ( 2, 1), ( 2, -1), ( 1, -2),
  1535. (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
  1536. rangen = range(n)
  1537. for i in range(m):
  1538. for j in rangen:
  1539. s = [c2i(i+io, j+jo) for io, jo in offsets
  1540. if 0 <= i+io < m and
  1541. 0 <= j+jo < n]
  1542. succs.append(s)
  1543. # Generate solutions.
  1544. def solve(self):
  1545. self._init_board()
  1546. for x in conjoin(self.squaregenerators):
  1547. yield x
  1548. def printsolution(self, x):
  1549. m, n = self.m, self.n
  1550. assert len(x) == m*n
  1551. w = len(str(m*n))
  1552. format = "%" + str(w) + "d"
  1553. squares = [[None] * n for i in range(m)]
  1554. k = 1
  1555. for i in x:
  1556. i1, j1 = self.index2coords(i)
  1557. squares[i1][j1] = format % k
  1558. k += 1
  1559. sep = "+" + ("-" * w + "+") * n
  1560. print(sep)
  1561. for i in range(m):
  1562. row = squares[i]
  1563. print("|" + "|".join(row) + "|")
  1564. print(sep)
  1565. conjoin_tests = """
  1566. Generate the 3-bit binary numbers in order. This illustrates dumbest-
  1567. possible use of conjoin, just to generate the full cross-product.
  1568. >>> for c in conjoin([lambda: iter((0, 1))] * 3):
  1569. ... print(c)
  1570. [0, 0, 0]
  1571. [0, 0, 1]
  1572. [0, 1, 0]
  1573. [0, 1, 1]
  1574. [1, 0, 0]
  1575. [1, 0, 1]
  1576. [1, 1, 0]
  1577. [1, 1, 1]
  1578. For efficiency in typical backtracking apps, conjoin() yields the same list
  1579. object each time. So if you want to save away a full account of its
  1580. generated sequence, you need to copy its results.
  1581. >>> def gencopy(iterator):
  1582. ... for x in iterator:
  1583. ... yield x[:]
  1584. >>> for n in range(10):
  1585. ... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n)))
  1586. ... print(n, len(all), all[0] == [0] * n, all[-1] == [1] * n)
  1587. 0 1 True True
  1588. 1 2 True True
  1589. 2 4 True True
  1590. 3 8 True True
  1591. 4 16 True True
  1592. 5 32 True True
  1593. 6 64 True True
  1594. 7 128 True True
  1595. 8 256 True True
  1596. 9 512 True True
  1597. And run an 8-queens solver.
  1598. >>> q = Queens(8)
  1599. >>> LIMIT = 2
  1600. >>> count = 0
  1601. >>> for row2col in q.solve():
  1602. ... count += 1
  1603. ... if count <= LIMIT:
  1604. ... print("Solution", count)
  1605. ... q.printsolution(row2col)
  1606. Solution 1
  1607. +-+-+-+-+-+-+-+-+
  1608. |Q| | | | | | | |
  1609. +-+-+-+-+-+-+-+-+
  1610. | | | | |Q| | | |
  1611. +-+-+-+-+-+-+-+-+
  1612. | | | | | | | |Q|
  1613. +-+-+-+-+-+-+-+-+
  1614. | | | | | |Q| | |
  1615. +-+-+-+-+-+-+-+-+
  1616. | | |Q| | | | | |
  1617. +-+-+-+-+-+-+-+-+
  1618. | | | | | | |Q| |
  1619. +-+-+-+-+-+-+-+-+
  1620. | |Q| | | | | | |
  1621. +-+-+-+-+-+-+-+-+
  1622. | | | |Q| | | | |
  1623. +-+-+-+-+-+-+-+-+
  1624. Solution 2
  1625. +-+-+-+-+-+-+-+-+
  1626. |Q| | | | | | | |
  1627. +-+-+-+-+-+-+-+-+
  1628. | | | | | |Q| | |
  1629. +-+-+-+-+-+-+-+-+
  1630. | | | | | | | |Q|
  1631. +-+-+-+-+-+-+-+-+
  1632. | | |Q| | | | | |
  1633. +-+-+-+-+-+-+-+-+
  1634. | | | | | | |Q| |
  1635. +-+-+-+-+-+-+-+-+
  1636. | | | |Q| | | | |
  1637. +-+-+-+-+-+-+-+-+
  1638. | |Q| | | | | | |
  1639. +-+-+-+-+-+-+-+-+
  1640. | | | | |Q| | | |
  1641. +-+-+-+-+-+-+-+-+
  1642. >>> print(count, "solutions in all.")
  1643. 92 solutions in all.
  1644. And run a Knight's Tour on a 10x10 board. Note that there are about
  1645. 20,000 solutions even on a 6x6 board, so don't dare run this to exhaustion.
  1646. >>> k = Knights(10, 10)
  1647. >>> LIMIT = 2
  1648. >>> count = 0
  1649. >>> for x in k.solve():
  1650. ... count += 1
  1651. ... if count <= LIMIT:
  1652. ... print("Solution", count)
  1653. ... k.printsolution(x)
  1654. ... else:
  1655. ... break
  1656. Solution 1
  1657. +---+---+---+---+---+---+---+---+---+---+
  1658. | 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
  1659. +---+---+---+---+---+---+---+---+---+---+
  1660. | 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
  1661. +---+---+---+---+---+---+---+---+---+---+
  1662. | 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
  1663. +---+---+---+---+---+---+---+---+---+---+
  1664. | 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
  1665. +---+---+---+---+---+---+---+---+---+---+
  1666. | 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
  1667. +---+---+---+---+---+---+---+---+---+---+
  1668. | 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
  1669. +---+---+---+---+---+---+---+---+---+---+
  1670. | 87| 98| 91| 80| 77| 84| 53| 46| 65| 44|
  1671. +---+---+---+---+---+---+---+---+---+---+
  1672. | 90| 23| 88| 95| 70| 79| 68| 83| 14| 17|
  1673. +---+---+---+---+---+---+---+---+---+---+
  1674. | 97| 92| 21| 78| 81| 94| 19| 16| 45| 66|
  1675. +---+---+---+---+---+---+---+---+---+---+
  1676. | 22| 89| 96| 93| 20| 69| 82| 67| 18| 15|
  1677. +---+---+---+---+---+---+---+---+---+---+
  1678. Solution 2
  1679. +---+---+---+---+---+---+---+---+---+---+
  1680. | 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
  1681. +---+---+---+---+---+---+---+---+---+---+
  1682. | 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
  1683. +---+---+---+---+---+---+---+---+---+---+
  1684. | 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
  1685. +---+---+---+---+---+---+---+---+---+---+
  1686. | 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
  1687. +---+---+---+---+---+---+---+---+---+---+
  1688. | 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
  1689. +---+---+---+---+---+---+---+---+---+---+
  1690. | 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
  1691. +---+---+---+---+---+---+---+---+---+---+
  1692. | 87| 98| 89| 80| 77| 84| 53| 46| 65| 44|
  1693. +---+---+---+---+---+---+---+---+---+---+
  1694. | 90| 23| 92| 95| 70| 79| 68| 83| 14| 17|
  1695. +---+---+---+---+---+---+---+---+---+---+
  1696. | 97| 88| 21| 78| 81| 94| 19| 16| 45| 66|
  1697. +---+---+---+---+---+---+---+---+---+---+
  1698. | 22| 91| 96| 93| 20| 69| 82| 67| 18| 15|
  1699. +---+---+---+---+---+---+---+---+---+---+
  1700. """
  1701. weakref_tests = """\
  1702. Generators are weakly referencable:
  1703. >>> import weakref
  1704. >>> def gen():
  1705. ... yield 'foo!'
  1706. ...
  1707. >>> wr = weakref.ref(gen)
  1708. >>> wr() is gen
  1709. True
  1710. >>> p = weakref.proxy(gen)
  1711. Generator-iterators are weakly referencable as well:
  1712. >>> gi = gen()
  1713. >>> wr = weakref.ref(gi)
  1714. >>> wr() is gi
  1715. True
  1716. >>> p = weakref.proxy(gi)
  1717. >>> list(p)
  1718. ['foo!']
  1719. """
  1720. coroutine_tests = """\
  1721. >>> from test.support import gc_collect
  1722. Sending a value into a started generator:
  1723. >>> def f():
  1724. ... print((yield 1))
  1725. ... yield 2
  1726. >>> g = f()
  1727. >>> next(g)
  1728. 1
  1729. >>> g.send(42)
  1730. 42
  1731. 2
  1732. Sending a value into a new generator produces a TypeError:
  1733. >>> f().send("foo")
  1734. Traceback (most recent call last):
  1735. ...
  1736. TypeError: can't send non-None value to a just-started generator
  1737. Yield by itself yields None:
  1738. >>> def f(): yield
  1739. >>> list(f())
  1740. [None]
  1741. Yield is allowed only in the outermost iterable in generator expression:
  1742. >>> def f(): list(i for i in [(yield 26)])
  1743. >>> type(f())
  1744. <class 'generator'>
  1745. A yield expression with augmented assignment.
  1746. >>> def coroutine(seq):
  1747. ... count = 0
  1748. ... while count < 200:
  1749. ... count += yield
  1750. ... seq.append(count)
  1751. >>> seq = []
  1752. >>> c = coroutine(seq)
  1753. >>> next(c)
  1754. >>> print(seq)
  1755. []
  1756. >>> c.send(10)
  1757. >>> print(seq)
  1758. [10]
  1759. >>> c.send(10)
  1760. >>> print(seq)
  1761. [10, 20]
  1762. >>> c.send(10)
  1763. >>> print(seq)
  1764. [10, 20, 30]
  1765. Check some syntax errors for yield expressions:
  1766. >>> f=lambda: (yield 1),(yield 2)
  1767. Traceback (most recent call last):
  1768. ...
  1769. SyntaxError: 'yield' outside function
  1770. # Pegen does not produce this error message yet
  1771. # >>> def f(): x = yield = y
  1772. # Traceback (most recent call last):
  1773. # ...
  1774. # SyntaxError: assignment to yield expression not possible
  1775. >>> def f(): (yield bar) = y
  1776. Traceback (most recent call last):
  1777. ...
  1778. SyntaxError: cannot assign to yield expression here. Maybe you meant '==' instead of '='?
  1779. >>> def f(): (yield bar) += y
  1780. Traceback (most recent call last):
  1781. ...
  1782. SyntaxError: 'yield expression' is an illegal expression for augmented assignment
  1783. Now check some throw() conditions:
  1784. >>> def f():
  1785. ... while True:
  1786. ... try:
  1787. ... print((yield))
  1788. ... except ValueError as v:
  1789. ... print("caught ValueError (%s)" % (v))
  1790. >>> import sys
  1791. >>> g = f()
  1792. >>> next(g)
  1793. >>> g.throw(ValueError) # type only
  1794. caught ValueError ()
  1795. >>> g.throw(ValueError("xyz")) # value only
  1796. caught ValueError (xyz)
  1797. >>> g.throw(ValueError, ValueError(1)) # value+matching type
  1798. caught ValueError (1)
  1799. >>> g.throw(ValueError, TypeError(1)) # mismatched type, rewrapped
  1800. caught ValueError (1)
  1801. >>> g.throw(ValueError, ValueError(1), None) # explicit None traceback
  1802. caught ValueError (1)
  1803. >>> g.throw(ValueError(1), "foo") # bad args
  1804. Traceback (most recent call last):
  1805. ...
  1806. TypeError: instance exception may not have a separate value
  1807. >>> g.throw(ValueError, "foo", 23) # bad args
  1808. Traceback (most recent call last):
  1809. ...
  1810. TypeError: throw() third argument must be a traceback object
  1811. >>> g.throw("abc")
  1812. Traceback (most recent call last):
  1813. ...
  1814. TypeError: exceptions must be classes or instances deriving from BaseException, not str
  1815. >>> g.throw(0)
  1816. Traceback (most recent call last):
  1817. ...
  1818. TypeError: exceptions must be classes or instances deriving from BaseException, not int
  1819. >>> g.throw(list)
  1820. Traceback (most recent call last):
  1821. ...
  1822. TypeError: exceptions must be classes or instances deriving from BaseException, not type
  1823. >>> def throw(g,exc):
  1824. ... try:
  1825. ... raise exc
  1826. ... except:
  1827. ... g.throw(*sys.exc_info())
  1828. >>> throw(g,ValueError) # do it with traceback included
  1829. caught ValueError ()
  1830. >>> g.send(1)
  1831. 1
  1832. >>> throw(g,TypeError) # terminate the generator
  1833. Traceback (most recent call last):
  1834. ...
  1835. TypeError
  1836. >>> print(g.gi_frame)
  1837. None
  1838. >>> g.send(2)
  1839. Traceback (most recent call last):
  1840. ...
  1841. StopIteration
  1842. >>> g.throw(ValueError,6) # throw on closed generator
  1843. Traceback (most recent call last):
  1844. ...
  1845. ValueError: 6
  1846. >>> f().throw(ValueError,7) # throw on just-opened generator
  1847. Traceback (most recent call last):
  1848. ...
  1849. ValueError: 7
  1850. Plain "raise" inside a generator should preserve the traceback (#13188).
  1851. The traceback should have 3 levels:
  1852. - g.throw()
  1853. - f()
  1854. - 1/0
  1855. >>> def f():
  1856. ... try:
  1857. ... yield
  1858. ... except:
  1859. ... raise
  1860. >>> g = f()
  1861. >>> try:
  1862. ... 1/0
  1863. ... except ZeroDivisionError as v:
  1864. ... try:
  1865. ... g.throw(v)
  1866. ... except Exception as w:
  1867. ... tb = w.__traceback__
  1868. >>> levels = 0
  1869. >>> while tb:
  1870. ... levels += 1
  1871. ... tb = tb.tb_next
  1872. >>> levels
  1873. 3
  1874. Now let's try closing a generator:
  1875. >>> def f():
  1876. ... try: yield
  1877. ... except GeneratorExit:
  1878. ... print("exiting")
  1879. >>> g = f()
  1880. >>> next(g)
  1881. >>> g.close()
  1882. exiting
  1883. >>> g.close() # should be no-op now
  1884. >>> f().close() # close on just-opened generator should be fine
  1885. >>> def f(): yield # an even simpler generator
  1886. >>> f().close() # close before opening
  1887. >>> g = f()
  1888. >>> next(g)
  1889. >>> g.close() # close normally
  1890. And finalization:
  1891. >>> def f():
  1892. ... try: yield
  1893. ... finally:
  1894. ... print("exiting")
  1895. >>> g = f()
  1896. >>> next(g)
  1897. >>> del g; gc_collect() # For PyPy or other GCs.
  1898. exiting
  1899. GeneratorExit is not caught by except Exception:
  1900. >>> def f():
  1901. ... try: yield
  1902. ... except Exception:
  1903. ... print('except')
  1904. ... finally:
  1905. ... print('finally')
  1906. >>> g = f()
  1907. >>> next(g)
  1908. >>> del g; gc_collect() # For PyPy or other GCs.
  1909. finally
  1910. Now let's try some ill-behaved generators:
  1911. >>> def f():
  1912. ... try: yield
  1913. ... except GeneratorExit:
  1914. ... yield "foo!"
  1915. >>> g = f()
  1916. >>> next(g)
  1917. >>> g.close()
  1918. Traceback (most recent call last):
  1919. ...
  1920. RuntimeError: generator ignored GeneratorExit
  1921. >>> g.close()
  1922. Our ill-behaved code should be invoked during GC:
  1923. >>> with support.catch_unraisable_exception() as cm:
  1924. ... g = f()
  1925. ... next(g)
  1926. ... del g
  1927. ...
  1928. ... cm.unraisable.exc_type == RuntimeError
  1929. ... "generator ignored GeneratorExit" in str(cm.unraisable.exc_value)
  1930. ... cm.unraisable.exc_traceback is not None
  1931. True
  1932. True
  1933. True
  1934. And errors thrown during closing should propagate:
  1935. >>> def f():
  1936. ... try: yield
  1937. ... except GeneratorExit:
  1938. ... raise TypeError("fie!")
  1939. >>> g = f()
  1940. >>> next(g)
  1941. >>> g.close()
  1942. Traceback (most recent call last):
  1943. ...
  1944. TypeError: fie!
  1945. Ensure that various yield expression constructs make their
  1946. enclosing function a generator:
  1947. >>> def f(): x += yield
  1948. >>> type(f())
  1949. <class 'generator'>
  1950. >>> def f(): x = yield
  1951. >>> type(f())
  1952. <class 'generator'>
  1953. >>> def f(): lambda x=(yield): 1
  1954. >>> type(f())
  1955. <class 'generator'>
  1956. >>> def f(d): d[(yield "a")] = d[(yield "b")] = 27
  1957. >>> data = [1,2]
  1958. >>> g = f(data)
  1959. >>> type(g)
  1960. <class 'generator'>
  1961. >>> g.send(None)
  1962. 'a'
  1963. >>> data
  1964. [1, 2]
  1965. >>> g.send(0)
  1966. 'b'
  1967. >>> data
  1968. [27, 2]
  1969. >>> try: g.send(1)
  1970. ... except StopIteration: pass
  1971. >>> data
  1972. [27, 27]
  1973. """
  1974. refleaks_tests = """
  1975. Prior to adding cycle-GC support to itertools.tee, this code would leak
  1976. references. We add it to the standard suite so the routine refleak-tests
  1977. would trigger if it starts being uncleanable again.
  1978. >>> import itertools
  1979. >>> def leak():
  1980. ... class gen:
  1981. ... def __iter__(self):
  1982. ... return self
  1983. ... def __next__(self):
  1984. ... return self.item
  1985. ... g = gen()
  1986. ... head, tail = itertools.tee(g)
  1987. ... g.item = head
  1988. ... return head
  1989. >>> it = leak()
  1990. Make sure to also test the involvement of the tee-internal teedataobject,
  1991. which stores returned items.
  1992. >>> item = next(it)
  1993. This test leaked at one point due to generator finalization/destruction.
  1994. It was copied from Lib/test/leakers/test_generator_cycle.py before the file
  1995. was removed.
  1996. >>> def leak():
  1997. ... def gen():
  1998. ... while True:
  1999. ... yield g
  2000. ... g = gen()
  2001. >>> leak()
  2002. This test isn't really generator related, but rather exception-in-cleanup
  2003. related. The coroutine tests (above) just happen to cause an exception in
  2004. the generator's __del__ (tp_del) method. We can also test for this
  2005. explicitly, without generators. We do have to redirect stderr to avoid
  2006. printing warnings and to doublecheck that we actually tested what we wanted
  2007. to test.
  2008. >>> from test import support
  2009. >>> class Leaker:
  2010. ... def __del__(self):
  2011. ... def invoke(message):
  2012. ... raise RuntimeError(message)
  2013. ... invoke("del failed")
  2014. ...
  2015. >>> with support.catch_unraisable_exception() as cm:
  2016. ... l = Leaker()
  2017. ... del l
  2018. ...
  2019. ... cm.unraisable.object == Leaker.__del__
  2020. ... cm.unraisable.exc_type == RuntimeError
  2021. ... str(cm.unraisable.exc_value) == "del failed"
  2022. ... cm.unraisable.exc_traceback is not None
  2023. True
  2024. True
  2025. True
  2026. True
  2027. These refleak tests should perhaps be in a testfile of their own,
  2028. test_generators just happened to be the test that drew these out.
  2029. """
  2030. __test__ = {"tut": tutorial_tests,
  2031. "pep": pep_tests,
  2032. "email": email_tests,
  2033. "fun": fun_tests,
  2034. "syntax": syntax_tests,
  2035. "conjoin": conjoin_tests,
  2036. "weakref": weakref_tests,
  2037. "coroutine": coroutine_tests,
  2038. "refleaks": refleaks_tests,
  2039. }
  2040. def load_tests(loader, tests, pattern):
  2041. tests.addTest(doctest.DocTestSuite())
  2042. return tests
  2043. if __name__ == "__main__":
  2044. unittest.main()