Debian Codegraph @

Lib/test/test_generators.py

raw
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 import types
10
11 from test import support
12
13 try:
14 import _testcapi
15 except ImportError:
16 _testcapi = None
17
18
19 # This tests to make sure that if a SIGINT arrives just before we send into a
20 # yield from chain, the KeyboardInterrupt is raised in the innermost
21 # generator (see bpo-30039).
22 @unittest.skipUnless(_testcapi is not None and
23 hasattr(_testcapi, "raise_SIGINT_then_send_None"),
24 "needs _testcapi.raise_SIGINT_then_send_None")
25 class SignalAndYieldFromTest(unittest.TestCase):
26
27 def generator1(self):
28 return (yield from self.generator2())
29
30 def generator2(self):
31 try:
32 yield
33 except KeyboardInterrupt:
34 return "PASSED"
35 else:
36 return "FAILED"
37
38 def test_raise_and_yield_from(self):
39 gen = self.generator1()
40 gen.send(None)
41 try:
42 _testcapi.raise_SIGINT_then_send_None(gen)
43 except BaseException as _exc:
44 exc = _exc
45 self.assertIs(type(exc), StopIteration)
46 self.assertEqual(exc.value, "PASSED")
47
48
49 class FinalizationTest(unittest.TestCase):
50
51 def test_frame_resurrect(self):
52 # A generator frame can be resurrected by a generator's finalization.
53 def gen():
54 nonlocal frame
55 try:
56 yield
57 finally:
58 frame = sys._getframe()
59
60 g = gen()
61 wr = weakref.ref(g)
62 next(g)
63 del g
64 support.gc_collect()
65 self.assertIs(wr(), None)
66 self.assertTrue(frame)
67 del frame
68 support.gc_collect()
69
70 def test_refcycle(self):
71 # A generator caught in a refcycle gets finalized anyway.
72 old_garbage = gc.garbage[:]
73 finalized = False
74 def gen():
75 nonlocal finalized
76 try:
77 g = yield
78 yield 1
79 finally:
80 finalized = True
81
82 g = gen()
83 next(g)
84 g.send(g)
85 self.assertGreater(sys.getrefcount(g), 2)
86 self.assertFalse(finalized)
87 del g
88 support.gc_collect()
89 self.assertTrue(finalized)
90 self.assertEqual(gc.garbage, old_garbage)
91
92 def test_lambda_generator(self):
93 # bpo-23192, gh-119897: Test that a lambda returning a generator behaves
94 # like the equivalent function
95 f = lambda: (yield 1)
96 self.assertIsInstance(f(), types.GeneratorType)
97 self.assertEqual(next(f()), 1)
98
99 def g(): return (yield 1)
100
101 # test 'yield from'
102 f2 = lambda: (yield from g())
103 def g2(): return (yield from g())
104
105 f3 = lambda: (yield from f())
106 def g3(): return (yield from f())
107
108 for gen_fun in (f, g, f2, g2, f3, g3):
109 gen = gen_fun()
110 self.assertEqual(next(gen), 1)
111 with self.assertRaises(StopIteration) as cm:
112 gen.send(2)
113 self.assertEqual(cm.exception.value, 2)
114
115 def test_exhausted_generator_frame_cycle(self):
116 def g():
117 yield
118
119 generator = g()
120 frame = generator.gi_frame
121 self.assertIsNone(frame.f_back)
122 next(generator)
123 self.assertIsNone(frame.f_back)
124 next(generator, None)
125 self.assertIsNone(frame.f_back)
126
127
128 class GeneratorTest(unittest.TestCase):
129
130 def test_name(self):
131 def func():
132 yield 1
133
134 # check generator names
135 gen = func()
136 self.assertEqual(gen.__name__, "func")
137 self.assertEqual(gen.__qualname__,
138 "GeneratorTest.test_name.<locals>.func")
139
140 # modify generator names
141 gen.__name__ = "name"
142 gen.__qualname__ = "qualname"
143 self.assertEqual(gen.__name__, "name")
144 self.assertEqual(gen.__qualname__, "qualname")
145
146 # generator names must be a string and cannot be deleted
147 self.assertRaises(TypeError, setattr, gen, '__name__', 123)
148 self.assertRaises(TypeError, setattr, gen, '__qualname__', 123)
149 self.assertRaises(TypeError, delattr, gen, '__name__')
150 self.assertRaises(TypeError, delattr, gen, '__qualname__')
151
152 # modify names of the function creating the generator
153 func.__qualname__ = "func_qualname"
154 func.__name__ = "func_name"
155 gen = func()
156 self.assertEqual(gen.__name__, "func_name")
157 self.assertEqual(gen.__qualname__, "func_qualname")
158
159 # unnamed generator
160 gen = (x for x in range(10))
161 self.assertEqual(gen.__name__,
162 "<genexpr>")
163 self.assertEqual(gen.__qualname__,
164 "GeneratorTest.test_name.<locals>.<genexpr>")
165
166 def test_copy(self):
167 def f():
168 yield 1
169 g = f()
170 with self.assertRaises(TypeError):
171 copy.copy(g)
172
173 def test_pickle(self):
174 def f():
175 yield 1
176 g = f()
177 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
178 with self.assertRaises((TypeError, pickle.PicklingError)):
179 pickle.dumps(g, proto)
180
181 def test_send_non_none_to_new_gen(self):
182 def f():
183 yield 1
184 g = f()
185 with self.assertRaises(TypeError):
186 g.send(0)
187 self.assertEqual(next(g), 1)
188
189 def test_handle_frame_object_in_creation(self):
190
191 #Attempt to expose partially constructed frames
192 #See https://github.com/python/cpython/issues/94262
193
194 def cb(*args):
195 inspect.stack()
196
197 def gen():
198 yield 1
199
200 thresholds = gc.get_threshold()
201
202 gc.callbacks.append(cb)
203 gc.set_threshold(1, 0, 0)
204 try:
205 gen()
206 finally:
207 gc.set_threshold(*thresholds)
208 gc.callbacks.pop()
209
210 class Sneaky:
211 def __del__(self):
212 inspect.stack()
213
214 sneaky = Sneaky()
215 sneaky._s = Sneaky()
216 sneaky._s._s = sneaky
217
218 gc.set_threshold(1, 0, 0)
219 try:
220 del sneaky
221 gen()
222 finally:
223 gc.set_threshold(*thresholds)
224
225 def test_ag_frame_f_back(self):
226 async def f():
227 yield
228 ag = f()
229 self.assertIsNone(ag.ag_frame.f_back)
230
231 def test_cr_frame_f_back(self):
232 async def f():
233 pass
234 cr = f()
235 self.assertIsNone(cr.cr_frame.f_back)
236 cr.close() # Suppress RuntimeWarning.
237
238 def test_gi_frame_f_back(self):
239 def f():
240 yield
241 gi = f()
242 self.assertIsNone(gi.gi_frame.f_back)
243
244 def test_issue103488(self):
245
246 def gen_raises():
247 yield
248 raise ValueError()
249
250 def loop():
251 try:
252 for _ in gen_raises():
253 if True is False:
254 return
255 except ValueError:
256 pass
257
258 #This should not raise
259 loop()
260
261 def test_close_clears_frame(self):
262 # gh-142766: Test that closing a generator clears its frame
263 class DetectDelete:
264 def __init__(self):
265 DetectDelete.deleted = False
266
267 def __del__(self):
268 DetectDelete.deleted = True
269
270 def generator(arg):
271 yield
272
273 # Test a freshly created generator (not suspended)
274 g = generator(DetectDelete())
275 g.close()
276 self.assertTrue(DetectDelete.deleted)
277
278 # Test a suspended generator
279 g = generator(DetectDelete())
280 next(g)
281 g.close()
282 self.assertTrue(DetectDelete.deleted)
283
284 # Clear via gi_frame.clear()
285 g = generator(DetectDelete())
286 g.gi_frame.clear()
287 self.assertTrue(DetectDelete.deleted)
288
289 class ModifyUnderlyingIterableTest(unittest.TestCase):
290 iterables = [
291 range(0),
292 range(20),
293 [1, 2, 3],
294 (2,),
295 {13, 48, 211},
296 frozenset((15, 8, 6)),
297 {1: 2, 3: 4},
298 ]
299
300 non_iterables = [
301 None,
302 42,
303 3.0,
304 2j,
305 ]
306
307 def genexpr(self):
308 return (x for x in range(10))
309
310 def genfunc(self):
311 def gen(it):
312 for x in it:
313 yield x
314 return gen(range(10))
315
316 def process_tests(self, get_generator):
317 for obj in self.iterables:
318 g_obj = get_generator(obj)
319 with self.subTest(g_obj=g_obj, obj=obj):
320 self.assertListEqual(list(g_obj), list(obj))
321
322 g_iter = get_generator(iter(obj))
323 with self.subTest(g_iter=g_iter, obj=obj):
324 self.assertListEqual(list(g_iter), list(obj))
325
326 err_regex = "'.*' object is not iterable"
327 for obj in self.non_iterables:
328 g_obj = get_generator(obj)
329 with self.subTest(g_obj=g_obj):
330 self.assertRaisesRegex(TypeError, err_regex, list, g_obj)
331
332 def test_modify_f_locals(self):
333 def modify_f_locals(g, local, obj):
334 g.gi_frame.f_locals[local] = obj
335 return g
336
337 def get_generator_genexpr(obj):
338 return modify_f_locals(self.genexpr(), '.0', obj)
339
340 def get_generator_genfunc(obj):
341 return modify_f_locals(self.genfunc(), 'it', obj)
342
343 self.process_tests(get_generator_genexpr)
344 self.process_tests(get_generator_genfunc)
345
346 def test_new_gen_from_gi_code(self):
347 def new_gen_from_gi_code(g, obj):
348 generator_func = types.FunctionType(g.gi_code, {})
349 return generator_func(obj)
350
351 def get_generator_genexpr(obj):
352 return new_gen_from_gi_code(self.genexpr(), obj)
353
354 def get_generator_genfunc(obj):
355 return new_gen_from_gi_code(self.genfunc(), obj)
356
357 self.process_tests(get_generator_genexpr)
358 self.process_tests(get_generator_genfunc)
359
360
361 class ExceptionTest(unittest.TestCase):
362 # Tests for the issue #23353: check that the currently handled exception
363 # is correctly saved/restored in PyEval_EvalFrameEx().
364
365 def test_except_throw(self):
366 def store_raise_exc_generator():
367 try:
368 self.assertIsNone(sys.exception())
369 yield
370 except Exception as exc:
371 # exception raised by gen.throw(exc)
372 self.assertIsInstance(sys.exception(), ValueError)
373 self.assertIsNone(exc.__context__)
374 yield
375
376 # ensure that the exception is not lost
377 self.assertIsInstance(sys.exception(), ValueError)
378 yield
379
380 # we should be able to raise back the ValueError
381 raise
382
383 make = store_raise_exc_generator()
384 next(make)
385
386 try:
387 raise ValueError()
388 except Exception as exc:
389 try:
390 make.throw(exc)
391 except Exception:
392 pass
393
394 next(make)
395 with self.assertRaises(ValueError) as cm:
396 next(make)
397 self.assertIsNone(cm.exception.__context__)
398
399 self.assertIsNone(sys.exception())
400
401 def test_except_next(self):
402 def gen():
403 self.assertIsInstance(sys.exception(), ValueError)
404 yield "done"
405
406 g = gen()
407 try:
408 raise ValueError
409 except Exception:
410 self.assertEqual(next(g), "done")
411 self.assertIsNone(sys.exception())
412
413 def test_except_gen_except(self):
414 def gen():
415 try:
416 self.assertIsNone(sys.exception())
417 yield
418 # we are called from "except ValueError:", TypeError must
419 # inherit ValueError in its context
420 raise TypeError()
421 except TypeError as exc:
422 self.assertIsInstance(sys.exception(), TypeError)
423 self.assertEqual(type(exc.__context__), ValueError)
424 # here we are still called from the "except ValueError:"
425 self.assertIsInstance(sys.exception(), ValueError)
426 yield
427 self.assertIsNone(sys.exception())
428 yield "done"
429
430 g = gen()
431 next(g)
432 try:
433 raise ValueError
434 except Exception:
435 next(g)
436
437 self.assertEqual(next(g), "done")
438 self.assertIsNone(sys.exception())
439
440 def test_nested_gen_except_loop(self):
441 def gen():
442 for i in range(100):
443 self.assertIsInstance(sys.exception(), TypeError)
444 yield "doing"
445
446 def outer():
447 try:
448 raise TypeError
449 except:
450 for x in gen():
451 yield x
452
453 try:
454 raise ValueError
455 except Exception:
456 for x in outer():
457 self.assertEqual(x, "doing")
458 self.assertEqual(sys.exception(), None)
459
460 def test_except_throw_exception_context(self):
461 def gen():
462 try:
463 try:
464 self.assertIsNone(sys.exception())
465 yield
466 except ValueError:
467 # we are called from "except ValueError:"
468 self.assertIsInstance(sys.exception(), ValueError)
469 raise TypeError()
470 except Exception as exc:
471 self.assertIsInstance(sys.exception(), TypeError)
472 self.assertEqual(type(exc.__context__), ValueError)
473 # we are still called from "except ValueError:"
474 self.assertIsInstance(sys.exception(), ValueError)
475 yield
476 self.assertIsNone(sys.exception())
477 yield "done"
478
479 g = gen()
480 next(g)
481 try:
482 raise ValueError
483 except Exception as exc:
484 g.throw(exc)
485
486 self.assertEqual(next(g), "done")
487 self.assertIsNone(sys.exception())
488
489 def test_except_throw_bad_exception(self):
490 class E(Exception):
491 def __new__(cls, *args, **kwargs):
492 return cls
493
494 def boring_generator():
495 yield
496
497 gen = boring_generator()
498
499 err_msg = 'should have returned an instance of BaseException'
500
501 with self.assertRaisesRegex(TypeError, err_msg):
502 gen.throw(E)
503
504 self.assertRaises(StopIteration, next, gen)
505
506 def generator():
507 with self.assertRaisesRegex(TypeError, err_msg):
508 yield
509
510 gen = generator()
511 next(gen)
512 with self.assertRaises(StopIteration):
513 gen.throw(E)
514
515 def test_gen_3_arg_deprecation_warning(self):
516 def g():
517 yield 42
518
519 gen = g()
520 with self.assertWarns(DeprecationWarning):
521 with self.assertRaises(TypeError):
522 gen.throw(TypeError, TypeError(24), None)
523
524 def test_stopiteration_error(self):
525 # See also PEP 479.
526
527 def gen():
528 raise StopIteration
529 yield
530
531 with self.assertRaisesRegex(RuntimeError, 'raised StopIteration'):
532 next(gen())
533
534 def test_tutorial_stopiteration(self):
535 # Raise StopIteration" stops the generator too:
536
537 def f():
538 yield 1
539 raise StopIteration
540 yield 2 # never reached
541
542 g = f()
543 self.assertEqual(next(g), 1)
544
545 with self.assertRaisesRegex(RuntimeError, 'raised StopIteration'):
546 next(g)
547
548 def test_return_tuple(self):
549 def g():
550 return (yield 1)
551
552 gen = g()
553 self.assertEqual(next(gen), 1)
554 with self.assertRaises(StopIteration) as cm:
555 gen.send((2,))
556 self.assertEqual(cm.exception.value, (2,))
557
558 def test_return_stopiteration(self):
559 def g():
560 return (yield 1)
561
562 gen = g()
563 self.assertEqual(next(gen), 1)
564 with self.assertRaises(StopIteration) as cm:
565 gen.send(StopIteration(2))
566 self.assertIsInstance(cm.exception.value, StopIteration)
567 self.assertEqual(cm.exception.value.value, 2)
568
569
570 class GeneratorCloseTest(unittest.TestCase):
571
572 def test_close_no_return_value(self):
573 def f():
574 yield
575
576 gen = f()
577 gen.send(None)
578 self.assertIsNone(gen.close())
579
580 def test_close_return_value(self):
581 def f():
582 try:
583 yield
584 # close() raises GeneratorExit here, which is caught
585 except GeneratorExit:
586 return 0
587
588 gen = f()
589 gen.send(None)
590 self.assertEqual(gen.close(), 0)
591
592 def test_close_not_catching_exit(self):
593 def f():
594 yield
595 # close() raises GeneratorExit here, which isn't caught and
596 # therefore propagates -- no return value
597 return 0
598
599 gen = f()
600 gen.send(None)
601 self.assertIsNone(gen.close())
602
603 def test_close_not_started(self):
604 def f():
605 try:
606 yield
607 except GeneratorExit:
608 return 0
609
610 gen = f()
611 self.assertIsNone(gen.close())
612
613 def test_close_exhausted(self):
614 def f():
615 try:
616 yield
617 except GeneratorExit:
618 return 0
619
620 gen = f()
621 next(gen)
622 with self.assertRaises(StopIteration):
623 next(gen)
624 self.assertIsNone(gen.close())
625
626 def test_close_closed(self):
627 def f():
628 try:
629 yield
630 except GeneratorExit:
631 return 0
632
633 gen = f()
634 gen.send(None)
635 self.assertEqual(gen.close(), 0)
636 self.assertIsNone(gen.close())
637
638 def test_close_raises(self):
639 def f():
640 try:
641 yield
642 except GeneratorExit:
643 pass
644 raise RuntimeError
645
646 gen = f()
647 gen.send(None)
648 with self.assertRaises(RuntimeError):
649 gen.close()
650
651 def test_close_releases_frame_locals(self):
652 # See gh-118272
653
654 class Foo:
655 pass
656
657 f = Foo()
658 f_wr = weakref.ref(f)
659
660 def genfn():
661 a = f
662 yield
663
664 g = genfn()
665 next(g)
666 del f
667 g.close()
668 support.gc_collect()
669 self.assertIsNone(f_wr())
670
671
672 # See https://github.com/python/cpython/issues/125723
673 class GeneratorDeallocTest(unittest.TestCase):
674 def test_frame_outlives_generator(self):
675 def g1():
676 a = 42
677 yield sys._getframe()
678
679 def g2():
680 a = 42
681 yield
682
683 def g3(obj):
684 a = 42
685 obj.frame = sys._getframe()
686 yield
687
688 class ObjectWithFrame():
689 def __init__(self):
690 self.frame = None
691
692 def get_frame(index):
693 if index == 1:
694 return next(g1())
695 elif index == 2:
696 gen = g2()
697 next(gen)
698 return gen.gi_frame
699 elif index == 3:
700 obj = ObjectWithFrame()
701 next(g3(obj))
702 return obj.frame
703 else:
704 return None
705
706 for index in (1, 2, 3):
707 with self.subTest(index=index):
708 frame = get_frame(index)
709 frame_locals = frame.f_locals
710 self.assertIn('a', frame_locals)
711 self.assertEqual(frame_locals['a'], 42)
712
713 def test_frame_locals_outlive_generator(self):
714 frame_locals1 = None
715
716 def g1():
717 nonlocal frame_locals1
718 frame_locals1 = sys._getframe().f_locals
719 a = 42
720 yield
721
722 def g2():
723 a = 42
724 yield sys._getframe().f_locals
725
726 def get_frame_locals(index):
727 if index == 1:
728 nonlocal frame_locals1
729 next(g1())
730 return frame_locals1
731 if index == 2:
732 return next(g2())
733 else:
734 return None
735
736 for index in (1, 2):
737 with self.subTest(index=index):
738 frame_locals = get_frame_locals(index)
739 self.assertIn('a', frame_locals)
740 self.assertEqual(frame_locals['a'], 42)
741
742 def test_frame_locals_outlive_generator_with_exec(self):
743 def g():
744 a = 42
745 yield locals(), sys._getframe().f_locals
746
747 locals_ = {'g': g}
748 for i in range(10):
749 exec("snapshot, live_locals = next(g())", locals=locals_)
750 for l in (locals_['snapshot'], locals_['live_locals']):
751 self.assertIn('a', l)
752 self.assertEqual(l['a'], 42)
753
754
755 class GeneratorThrowTest(unittest.TestCase):
756
757 def test_exception_context_with_yield(self):
758 def f():
759 try:
760 raise KeyError('a')
761 except Exception:
762 yield
763
764 gen = f()
765 gen.send(None)
766 with self.assertRaises(ValueError) as cm:
767 gen.throw(ValueError)
768 context = cm.exception.__context__
769 self.assertEqual((type(context), context.args), (KeyError, ('a',)))
770
771 def test_exception_context_with_yield_inside_generator(self):
772 # Check that the context is also available from inside the generator
773 # with yield, as opposed to outside.
774 def f():
775 try:
776 raise KeyError('a')
777 except Exception:
778 try:
779 yield
780 except Exception as exc:
781 self.assertEqual(type(exc), ValueError)
782 context = exc.__context__
783 self.assertEqual((type(context), context.args),
784 (KeyError, ('a',)))
785 yield 'b'
786
787 gen = f()
788 gen.send(None)
789 actual = gen.throw(ValueError)
790 # This ensures that the assertions inside were executed.
791 self.assertEqual(actual, 'b')
792
793 def test_exception_context_with_yield_from(self):
794 def f():
795 yield
796
797 def g():
798 try:
799 raise KeyError('a')
800 except Exception:
801 yield from f()
802
803 gen = g()
804 gen.send(None)
805 with self.assertRaises(ValueError) as cm:
806 gen.throw(ValueError)
807 context = cm.exception.__context__
808 self.assertEqual((type(context), context.args), (KeyError, ('a',)))
809
810 def test_exception_context_with_yield_from_with_context_cycle(self):
811 # Check trying to create an exception context cycle:
812 # https://bugs.python.org/issue40696
813 has_cycle = None
814
815 def f():
816 yield
817
818 def g(exc):
819 nonlocal has_cycle
820 try:
821 raise exc
822 except Exception:
823 try:
824 yield from f()
825 except Exception as exc:
826 has_cycle = (exc is exc.__context__)
827 yield
828
829 exc = KeyError('a')
830 gen = g(exc)
831 gen.send(None)
832 gen.throw(exc)
833 # This also distinguishes from the initial has_cycle=None.
834 self.assertEqual(has_cycle, False)
835
836 def test_throw_after_none_exc_type(self):
837 def g():
838 try:
839 raise KeyError
840 except KeyError:
841 pass
842
843 try:
844 yield
845 except Exception:
846 raise RuntimeError
847
848 gen = g()
849 gen.send(None)
850 with self.assertRaises(RuntimeError) as cm:
851 gen.throw(ValueError)
852
853
854 class GeneratorStackTraceTest(unittest.TestCase):
855
856 def check_stack_names(self, frame, expected):
857 names = []
858 while frame:
859 name = frame.f_code.co_name
860 # Stop checking frames when we get to our test helper.
861 if name.startswith('check_') or name.startswith('call_'):
862 break
863
864 names.append(name)
865 frame = frame.f_back
866
867 self.assertEqual(names, expected)
868
869 def check_yield_from_example(self, call_method):
870 def f():
871 self.check_stack_names(sys._getframe(), ['f', 'g'])
872 try:
873 yield
874 except Exception:
875 pass
876 self.check_stack_names(sys._getframe(), ['f', 'g'])
877
878 def g():
879 self.check_stack_names(sys._getframe(), ['g'])
880 yield from f()
881 self.check_stack_names(sys._getframe(), ['g'])
882
883 gen = g()
884 gen.send(None)
885 try:
886 call_method(gen)
887 except StopIteration:
888 pass
889
890 def test_send_with_yield_from(self):
891 def call_send(gen):
892 gen.send(None)
893
894 self.check_yield_from_example(call_send)
895
896 def test_throw_with_yield_from(self):
897 def call_throw(gen):
898 gen.throw(RuntimeError)
899
900 self.check_yield_from_example(call_throw)
901
902
903 class YieldFromTests(unittest.TestCase):
904 def test_generator_gi_yieldfrom(self):
905 def a():
906 self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_RUNNING)
907 self.assertIsNone(gen_b.gi_yieldfrom)
908 yield
909 self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_RUNNING)
910 self.assertIsNone(gen_b.gi_yieldfrom)
911
912 def b():
913 self.assertIsNone(gen_b.gi_yieldfrom)
914 yield from a()
915 self.assertIsNone(gen_b.gi_yieldfrom)
916 yield
917 self.assertIsNone(gen_b.gi_yieldfrom)
918
919 gen_b = b()
920 self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_CREATED)
921 self.assertIsNone(gen_b.gi_yieldfrom)
922
923 gen_b.send(None)
924 self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_SUSPENDED)
925 self.assertEqual(gen_b.gi_yieldfrom.gi_code.co_name, 'a')
926
927 gen_b.send(None)
928 self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_SUSPENDED)
929 self.assertIsNone(gen_b.gi_yieldfrom)
930
931 [] = gen_b # Exhaust generator
932 self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_CLOSED)
933 self.assertIsNone(gen_b.gi_yieldfrom)
934
935
936 tutorial_tests = """
937 Let's try a simple generator:
938
939 >>> def f():
940 ... yield 1
941 ... yield 2
942
943 >>> for i in f():
944 ... print(i)
945 1
946 2
947 >>> g = f()
948 >>> next(g)
949 1
950 >>> next(g)
951 2
952
953 "Falling off the end" stops the generator:
954
955 >>> next(g)
956 Traceback (most recent call last):
957 File "<stdin>", line 1, in ?
958 File "<stdin>", line 2, in g
959 StopIteration
960
961 "return" also stops the generator:
962
963 >>> def f():
964 ... yield 1
965 ... return
966 ... yield 2 # never reached
967 ...
968 >>> g = f()
969 >>> next(g)
970 1
971 >>> next(g)
972 Traceback (most recent call last):
973 File "<stdin>", line 1, in ?
974 File "<stdin>", line 3, in f
975 StopIteration
976 >>> next(g) # once stopped, can't be resumed
977 Traceback (most recent call last):
978 File "<stdin>", line 1, in ?
979 StopIteration
980
981 However, "return" and StopIteration are not exactly equivalent:
982
983 >>> def g1():
984 ... try:
985 ... return
986 ... except:
987 ... yield 1
988 ...
989 >>> list(g1())
990 []
991
992 >>> def g2():
993 ... try:
994 ... raise StopIteration
995 ... except:
996 ... yield 42
997 >>> print(list(g2()))
998 [42]
999
1000 This may be surprising at first:
1001
1002 >>> def g3():
1003 ... try:
1004 ... return
1005 ... finally:
1006 ... yield 1
1007 ...
1008 >>> list(g3())
1009 [1]
1010
1011 Let's create an alternate range() function implemented as a generator:
1012
1013 >>> def yrange(n):
1014 ... for i in range(n):
1015 ... yield i
1016 ...
1017 >>> list(yrange(5))
1018 [0, 1, 2, 3, 4]
1019
1020 Generators always return to the most recent caller:
1021
1022 >>> def creator():
1023 ... r = yrange(5)
1024 ... print("creator", next(r))
1025 ... return r
1026 ...
1027 >>> def caller():
1028 ... r = creator()
1029 ... for i in r:
1030 ... print("caller", i)
1031 ...
1032 >>> caller()
1033 creator 0
1034 caller 1
1035 caller 2
1036 caller 3
1037 caller 4
1038
1039 Generators can call other generators:
1040
1041 >>> def zrange(n):
1042 ... for i in yrange(n):
1043 ... yield i
1044 ...
1045 >>> list(zrange(5))
1046 [0, 1, 2, 3, 4]
1047
1048 """
1049
1050 # The examples from PEP 255.
1051
1052 pep_tests = """
1053
1054 Specification: Yield
1055
1056 Restriction: A generator cannot be resumed while it is actively
1057 running:
1058
1059 >>> def g():
1060 ... i = next(me)
1061 ... yield i
1062 >>> me = g()
1063 >>> next(me)
1064 Traceback (most recent call last):
1065 ...
1066 File "<string>", line 2, in g
1067 ValueError: generator already executing
1068
1069 Specification: Return
1070
1071 Note that return isn't always equivalent to raising StopIteration: the
1072 difference lies in how enclosing try/except constructs are treated.
1073 For example,
1074
1075 >>> def f1():
1076 ... try:
1077 ... return
1078 ... except:
1079 ... yield 1
1080 >>> print(list(f1()))
1081 []
1082
1083 because, as in any function, return simply exits, but
1084
1085 >>> def f2():
1086 ... try:
1087 ... raise StopIteration
1088 ... except:
1089 ... yield 42
1090 >>> print(list(f2()))
1091 [42]
1092
1093 because StopIteration is captured by a bare "except", as is any
1094 exception.
1095
1096 Specification: Generators and Exception Propagation
1097
1098 >>> def f():
1099 ... return 1//0
1100 >>> def g():
1101 ... yield f() # the zero division exception propagates
1102 ... yield 42 # and we'll never get here
1103 >>> k = g()
1104 >>> next(k)
1105 Traceback (most recent call last):
1106 File "<stdin>", line 1, in ?
1107 File "<stdin>", line 2, in g
1108 File "<stdin>", line 2, in f
1109 ZeroDivisionError: integer division or modulo by zero
1110 >>> next(k) # and the generator cannot be resumed
1111 Traceback (most recent call last):
1112 File "<stdin>", line 1, in ?
1113 StopIteration
1114 >>>
1115
1116 Specification: Try/Except/Finally
1117
1118 >>> def f():
1119 ... try:
1120 ... yield 1
1121 ... try:
1122 ... yield 2
1123 ... 1//0
1124 ... yield 3 # never get here
1125 ... except ZeroDivisionError:
1126 ... yield 4
1127 ... yield 5
1128 ... raise
1129 ... except:
1130 ... yield 6
1131 ... yield 7 # the "raise" above stops this
1132 ... except:
1133 ... yield 8
1134 ... yield 9
1135 ... try:
1136 ... x = 12
1137 ... finally:
1138 ... yield 10
1139 ... yield 11
1140 >>> print(list(f()))
1141 [1, 2, 4, 5, 8, 9, 10, 11]
1142 >>>
1143
1144 Guido's binary tree example.
1145
1146 >>> # A binary tree class.
1147 >>> class Tree:
1148 ...
1149 ... def __init__(self, label, left=None, right=None):
1150 ... self.label = label
1151 ... self.left = left
1152 ... self.right = right
1153 ...
1154 ... def __repr__(self, level=0, indent=" "):
1155 ... s = level*indent + repr(self.label)
1156 ... if self.left:
1157 ... s = s + "\\n" + self.left.__repr__(level+1, indent)
1158 ... if self.right:
1159 ... s = s + "\\n" + self.right.__repr__(level+1, indent)
1160 ... return s
1161 ...
1162 ... def __iter__(self):
1163 ... return inorder(self)
1164
1165 >>> # Create a Tree from a list.
1166 >>> def tree(list):
1167 ... n = len(list)
1168 ... if n == 0:
1169 ... return []
1170 ... i = n // 2
1171 ... return Tree(list[i], tree(list[:i]), tree(list[i+1:]))
1172
1173 >>> # Show it off: create a tree.
1174 >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
1175
1176 >>> # A recursive generator that generates Tree labels in in-order.
1177 >>> def inorder(t):
1178 ... if t:
1179 ... for x in inorder(t.left):
1180 ... yield x
1181 ... yield t.label
1182 ... for x in inorder(t.right):
1183 ... yield x
1184
1185 >>> # Show it off: create a tree.
1186 >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
1187 >>> # Print the nodes of the tree in in-order.
1188 >>> for x in t:
1189 ... print(' '+x, end='')
1190 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
1191
1192 >>> # A non-recursive generator.
1193 >>> def inorder(node):
1194 ... stack = []
1195 ... while node:
1196 ... while node.left:
1197 ... stack.append(node)
1198 ... node = node.left
1199 ... yield node.label
1200 ... while not node.right:
1201 ... try:
1202 ... node = stack.pop()
1203 ... except IndexError:
1204 ... return
1205 ... yield node.label
1206 ... node = node.right
1207
1208 >>> # Exercise the non-recursive generator.
1209 >>> for x in t:
1210 ... print(' '+x, end='')
1211 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
1212
1213 """
1214
1215 # Examples from Iterator-List and Python-Dev and c.l.py.
1216
1217 email_tests = """
1218
1219 The difference between yielding None and returning it.
1220
1221 >>> def g():
1222 ... for i in range(3):
1223 ... yield None
1224 ... yield None
1225 ... return
1226 >>> list(g())
1227 [None, None, None, None]
1228
1229 Ensure that explicitly raising StopIteration acts like any other exception
1230 in try/except, not like a return.
1231
1232 >>> def g():
1233 ... yield 1
1234 ... try:
1235 ... raise StopIteration
1236 ... except:
1237 ... yield 2
1238 ... yield 3
1239 >>> list(g())
1240 [1, 2, 3]
1241
1242 Next one was posted to c.l.py.
1243
1244 >>> def gcomb(x, k):
1245 ... "Generate all combinations of k elements from list x."
1246 ...
1247 ... if k > len(x):
1248 ... return
1249 ... if k == 0:
1250 ... yield []
1251 ... else:
1252 ... first, rest = x[0], x[1:]
1253 ... # A combination does or doesn't contain first.
1254 ... # If it does, the remainder is a k-1 comb of rest.
1255 ... for c in gcomb(rest, k-1):
1256 ... c.insert(0, first)
1257 ... yield c
1258 ... # If it doesn't contain first, it's a k comb of rest.
1259 ... for c in gcomb(rest, k):
1260 ... yield c
1261
1262 >>> seq = list(range(1, 5))
1263 >>> for k in range(len(seq) + 2):
1264 ... print("%d-combs of %s:" % (k, seq))
1265 ... for c in gcomb(seq, k):
1266 ... print(" ", c)
1267 0-combs of [1, 2, 3, 4]:
1268 []
1269 1-combs of [1, 2, 3, 4]:
1270 [1]
1271 [2]
1272 [3]
1273 [4]
1274 2-combs of [1, 2, 3, 4]:
1275 [1, 2]
1276 [1, 3]
1277 [1, 4]
1278 [2, 3]
1279 [2, 4]
1280 [3, 4]
1281 3-combs of [1, 2, 3, 4]:
1282 [1, 2, 3]
1283 [1, 2, 4]
1284 [1, 3, 4]
1285 [2, 3, 4]
1286 4-combs of [1, 2, 3, 4]:
1287 [1, 2, 3, 4]
1288 5-combs of [1, 2, 3, 4]:
1289
1290 From the Iterators list, about the types of these things.
1291
1292 >>> def g():
1293 ... yield 1
1294 ...
1295 >>> type(g)
1296 <class 'function'>
1297 >>> i = g()
1298 >>> type(i)
1299 <class 'generator'>
1300 >>> [s for s in dir(i) if not s.startswith('_')]
1301 ['close', 'gi_code', 'gi_frame', 'gi_running', 'gi_suspended', 'gi_yieldfrom', 'send', 'throw']
1302 >>> from test.support import HAVE_DOCSTRINGS
1303 >>> print(i.__next__.__doc__ if HAVE_DOCSTRINGS else 'Implement next(self).')
1304 Implement next(self).
1305 >>> iter(i) is i
1306 True
1307 >>> import types
1308 >>> isinstance(i, types.GeneratorType)
1309 True
1310
1311 And more, added later.
1312
1313 >>> i.gi_running
1314 0
1315 >>> type(i.gi_frame)
1316 <class 'frame'>
1317 >>> i.gi_running = 42
1318 Traceback (most recent call last):
1319 ...
1320 AttributeError: attribute 'gi_running' of 'generator' objects is not writable
1321 >>> def g():
1322 ... yield me.gi_running
1323 >>> me = g()
1324 >>> me.gi_running
1325 0
1326 >>> next(me)
1327 1
1328 >>> me.gi_running
1329 0
1330
1331 A clever union-find implementation from c.l.py, due to David Eppstein.
1332 Sent: Friday, June 29, 2001 12:16 PM
1333 To: [email protected]
1334 Subject: Re: PEP 255: Simple Generators
1335
1336 >>> class disjointSet:
1337 ... def __init__(self, name):
1338 ... self.name = name
1339 ... self.parent = None
1340 ... self.generator = self.generate()
1341 ...
1342 ... def generate(self):
1343 ... while not self.parent:
1344 ... yield self
1345 ... for x in self.parent.generator:
1346 ... yield x
1347 ...
1348 ... def find(self):
1349 ... return next(self.generator)
1350 ...
1351 ... def union(self, parent):
1352 ... if self.parent:
1353 ... raise ValueError("Sorry, I'm not a root!")
1354 ... self.parent = parent
1355 ...
1356 ... def __str__(self):
1357 ... return self.name
1358
1359 >>> names = "ABCDEFGHIJKLM"
1360 >>> sets = [disjointSet(name) for name in names]
1361 >>> roots = sets[:]
1362
1363 >>> import random
1364 >>> gen = random.Random(42)
1365 >>> while 1:
1366 ... for s in sets:
1367 ... print(" %s->%s" % (s, s.find()), end='')
1368 ... print()
1369 ... if len(roots) > 1:
1370 ... s1 = gen.choice(roots)
1371 ... roots.remove(s1)
1372 ... s2 = gen.choice(roots)
1373 ... s1.union(s2)
1374 ... print("merged", s1, "into", s2)
1375 ... else:
1376 ... break
1377 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
1378 merged K into B
1379 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
1380 merged A into F
1381 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
1382 merged E into F
1383 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
1384 merged D into C
1385 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
1386 merged M into C
1387 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
1388 merged J into B
1389 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
1390 merged B into C
1391 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
1392 merged F into G
1393 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
1394 merged L into C
1395 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
1396 merged G into I
1397 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
1398 merged I into H
1399 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
1400 merged C into H
1401 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
1402
1403 """
1404 # Emacs turd '
1405
1406 # Fun tests (for sufficiently warped notions of "fun").
1407
1408 fun_tests = """
1409
1410 Build up to a recursive Sieve of Eratosthenes generator.
1411
1412 >>> def firstn(g, n):
1413 ... return [next(g) for i in range(n)]
1414
1415 >>> def intsfrom(i):
1416 ... while 1:
1417 ... yield i
1418 ... i += 1
1419
1420 >>> firstn(intsfrom(5), 7)
1421 [5, 6, 7, 8, 9, 10, 11]
1422
1423 >>> def exclude_multiples(n, ints):
1424 ... for i in ints:
1425 ... if i % n:
1426 ... yield i
1427
1428 >>> firstn(exclude_multiples(3, intsfrom(1)), 6)
1429 [1, 2, 4, 5, 7, 8]
1430
1431 >>> def sieve(ints):
1432 ... prime = next(ints)
1433 ... yield prime
1434 ... not_divisible_by_prime = exclude_multiples(prime, ints)
1435 ... for p in sieve(not_divisible_by_prime):
1436 ... yield p
1437
1438 >>> primes = sieve(intsfrom(2))
1439 >>> firstn(primes, 20)
1440 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
1441
1442
1443 Another famous problem: generate all integers of the form
1444 2**i * 3**j * 5**k
1445 in increasing order, where i,j,k >= 0. Trickier than it may look at first!
1446 Try writing it without generators, and correctly, and without generating
1447 3 internal results for each result output.
1448
1449 >>> def times(n, g):
1450 ... for i in g:
1451 ... yield n * i
1452 >>> firstn(times(10, intsfrom(1)), 10)
1453 [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
1454
1455 >>> def merge(g, h):
1456 ... ng = next(g)
1457 ... nh = next(h)
1458 ... while 1:
1459 ... if ng < nh:
1460 ... yield ng
1461 ... ng = next(g)
1462 ... elif ng > nh:
1463 ... yield nh
1464 ... nh = next(h)
1465 ... else:
1466 ... yield ng
1467 ... ng = next(g)
1468 ... nh = next(h)
1469
1470 The following works, but is doing a whale of a lot of redundant work --
1471 it's not clear how to get the internal uses of m235 to share a single
1472 generator. Note that me_times2 (etc) each need to see every element in the
1473 result sequence. So this is an example where lazy lists are more natural
1474 (you can look at the head of a lazy list any number of times).
1475
1476 >>> def m235():
1477 ... yield 1
1478 ... me_times2 = times(2, m235())
1479 ... me_times3 = times(3, m235())
1480 ... me_times5 = times(5, m235())
1481 ... for i in merge(merge(me_times2,
1482 ... me_times3),
1483 ... me_times5):
1484 ... yield i
1485
1486 Don't print "too many" of these -- the implementation above is extremely
1487 inefficient: each call of m235() leads to 3 recursive calls, and in
1488 turn each of those 3 more, and so on, and so on, until we've descended
1489 enough levels to satisfy the print stmts. Very odd: when I printed 5
1490 lines of results below, this managed to screw up Win98's malloc in "the
1491 usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting
1492 address space, and it *looked* like a very slow leak.
1493
1494 >>> result = m235()
1495 >>> for i in range(3):
1496 ... print(firstn(result, 15))
1497 [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
1498 [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
1499 [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
1500
1501 Heh. Here's one way to get a shared list, complete with an excruciating
1502 namespace renaming trick. The *pretty* part is that the times() and merge()
1503 functions can be reused as-is, because they only assume their stream
1504 arguments are iterable -- a LazyList is the same as a generator to times().
1505
1506 >>> class LazyList:
1507 ... def __init__(self, g):
1508 ... self.sofar = []
1509 ... self.fetch = g.__next__
1510 ...
1511 ... def __getitem__(self, i):
1512 ... sofar, fetch = self.sofar, self.fetch
1513 ... while i >= len(sofar):
1514 ... sofar.append(fetch())
1515 ... return sofar[i]
1516
1517 >>> def m235():
1518 ... yield 1
1519 ... # Gack: m235 below actually refers to a LazyList.
1520 ... me_times2 = times(2, m235)
1521 ... me_times3 = times(3, m235)
1522 ... me_times5 = times(5, m235)
1523 ... for i in merge(merge(me_times2,
1524 ... me_times3),
1525 ... me_times5):
1526 ... yield i
1527
1528 Print as many of these as you like -- *this* implementation is memory-
1529 efficient.
1530
1531 >>> m235 = LazyList(m235())
1532 >>> for i in range(5):
1533 ... print([m235[j] for j in range(15*i, 15*(i+1))])
1534 [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
1535 [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
1536 [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
1537 [200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
1538 [400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
1539
1540 Ye olde Fibonacci generator, LazyList style.
1541
1542 >>> def fibgen(a, b):
1543 ...
1544 ... def sum(g, h):
1545 ... while 1:
1546 ... yield next(g) + next(h)
1547 ...
1548 ... def tail(g):
1549 ... next(g) # throw first away
1550 ... for x in g:
1551 ... yield x
1552 ...
1553 ... yield a
1554 ... yield b
1555 ... for s in sum(iter(fib),
1556 ... tail(iter(fib))):
1557 ... yield s
1558
1559 >>> fib = LazyList(fibgen(1, 2))
1560 >>> firstn(iter(fib), 17)
1561 [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
1562
1563
1564 Running after your tail with itertools.tee (new in version 2.4)
1565
1566 The algorithms "m235" (Hamming) and Fibonacci presented above are both
1567 examples of a whole family of FP (functional programming) algorithms
1568 where a function produces and returns a list while the production algorithm
1569 suppose the list as already produced by recursively calling itself.
1570 For these algorithms to work, they must:
1571
1572 - produce at least a first element without presupposing the existence of
1573 the rest of the list
1574 - produce their elements in a lazy manner
1575
1576 To work efficiently, the beginning of the list must not be recomputed over
1577 and over again. This is ensured in most FP languages as a built-in feature.
1578 In python, we have to explicitly maintain a list of already computed results
1579 and abandon genuine recursivity.
1580
1581 This is what had been attempted above with the LazyList class. One problem
1582 with that class is that it keeps a list of all of the generated results and
1583 therefore continually grows. This partially defeats the goal of the generator
1584 concept, viz. produce the results only as needed instead of producing them
1585 all and thereby wasting memory.
1586
1587 Thanks to itertools.tee, it is now clear "how to get the internal uses of
1588 m235 to share a single generator".
1589
1590 >>> from itertools import tee
1591 >>> def m235():
1592 ... def _m235():
1593 ... yield 1
1594 ... for n in merge(times(2, m2),
1595 ... merge(times(3, m3),
1596 ... times(5, m5))):
1597 ... yield n
1598 ... m1 = _m235()
1599 ... m2, m3, m5, mRes = tee(m1, 4)
1600 ... return mRes
1601
1602 >>> it = m235()
1603 >>> for i in range(5):
1604 ... print(firstn(it, 15))
1605 [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
1606 [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
1607 [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
1608 [200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
1609 [400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
1610
1611 The "tee" function does just what we want. It internally keeps a generated
1612 result for as long as it has not been "consumed" from all of the duplicated
1613 iterators, whereupon it is deleted. You can therefore print the hamming
1614 sequence during hours without increasing memory usage, or very little.
1615
1616 The beauty of it is that recursive running-after-their-tail FP algorithms
1617 are quite straightforwardly expressed with this Python idiom.
1618
1619 Ye olde Fibonacci generator, tee style.
1620
1621 >>> def fib():
1622 ...
1623 ... def _isum(g, h):
1624 ... while 1:
1625 ... yield next(g) + next(h)
1626 ...
1627 ... def _fib():
1628 ... yield 1
1629 ... yield 2
1630 ... next(fibTail) # throw first away
1631 ... for res in _isum(fibHead, fibTail):
1632 ... yield res
1633 ...
1634 ... realfib = _fib()
1635 ... fibHead, fibTail, fibRes = tee(realfib, 3)
1636 ... return fibRes
1637
1638 >>> firstn(fib(), 17)
1639 [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
1640
1641 """
1642
1643 # syntax_tests mostly provokes SyntaxErrors. Also fiddling with #if 0
1644 # hackery.
1645
1646 syntax_tests = """
1647
1648 These are fine:
1649
1650 >>> def f():
1651 ... yield 1
1652 ... return
1653
1654 >>> def f():
1655 ... try:
1656 ... yield 1
1657 ... finally:
1658 ... pass
1659
1660 >>> def f():
1661 ... try:
1662 ... try:
1663 ... 1//0
1664 ... except ZeroDivisionError:
1665 ... yield 666
1666 ... except:
1667 ... pass
1668 ... finally:
1669 ... pass
1670
1671 >>> def f():
1672 ... try:
1673 ... try:
1674 ... yield 12
1675 ... 1//0
1676 ... except ZeroDivisionError:
1677 ... yield 666
1678 ... except:
1679 ... try:
1680 ... x = 12
1681 ... finally:
1682 ... yield 12
1683 ... except:
1684 ... return
1685 >>> list(f())
1686 [12, 666]
1687
1688 >>> def f():
1689 ... yield
1690 >>> type(f())
1691 <class 'generator'>
1692
1693
1694 >>> def f():
1695 ... if 0:
1696 ... yield
1697 >>> type(f())
1698 <class 'generator'>
1699
1700
1701 >>> def f():
1702 ... if 0:
1703 ... yield 1
1704 >>> type(f())
1705 <class 'generator'>
1706
1707 >>> def f():
1708 ... if "":
1709 ... yield None
1710 >>> type(f())
1711 <class 'generator'>
1712
1713 >>> def f():
1714 ... return
1715 ... try:
1716 ... if x==4:
1717 ... pass
1718 ... elif 0:
1719 ... try:
1720 ... 1//0
1721 ... except SyntaxError:
1722 ... pass
1723 ... else:
1724 ... if 0:
1725 ... while 12:
1726 ... x += 1
1727 ... yield 2 # don't blink
1728 ... f(a, b, c, d, e)
1729 ... else:
1730 ... pass
1731 ... except:
1732 ... x = 1
1733 ... return
1734 >>> type(f())
1735 <class 'generator'>
1736
1737 >>> def f():
1738 ... if 0:
1739 ... def g():
1740 ... yield 1
1741 ...
1742 >>> type(f())
1743 <class 'NoneType'>
1744
1745 >>> def f():
1746 ... if 0:
1747 ... class C:
1748 ... def __init__(self):
1749 ... yield 1
1750 ... def f(self):
1751 ... yield 2
1752 >>> type(f())
1753 <class 'NoneType'>
1754
1755 >>> def f():
1756 ... if 0:
1757 ... return
1758 ... if 0:
1759 ... yield 2
1760 >>> type(f())
1761 <class 'generator'>
1762
1763 This one caused a crash (see SF bug 567538):
1764
1765 >>> def f():
1766 ... for i in range(3):
1767 ... try:
1768 ... continue
1769 ... finally:
1770 ... yield i
1771 ...
1772 >>> g = f()
1773 >>> print(next(g))
1774 0
1775 >>> print(next(g))
1776 1
1777 >>> print(next(g))
1778 2
1779 >>> print(next(g))
1780 Traceback (most recent call last):
1781 StopIteration
1782
1783
1784 Test the gi_code attribute
1785
1786 >>> def f():
1787 ... yield 5
1788 ...
1789 >>> g = f()
1790 >>> g.gi_code is f.__code__
1791 True
1792 >>> next(g)
1793 5
1794 >>> next(g)
1795 Traceback (most recent call last):
1796 StopIteration
1797 >>> g.gi_code is f.__code__
1798 True
1799
1800
1801 Test the __name__ attribute and the repr()
1802
1803 >>> def f():
1804 ... yield 5
1805 ...
1806 >>> g = f()
1807 >>> g.__name__
1808 'f'
1809 >>> repr(g) # doctest: +ELLIPSIS
1810 '<generator object f at ...>'
1811
1812 Lambdas shouldn't have their usual return behavior.
1813
1814 >>> x = lambda: (yield 1)
1815 >>> list(x())
1816 [1]
1817
1818 >>> x = lambda: ((yield 1), (yield 2))
1819 >>> list(x())
1820 [1, 2]
1821 """
1822
1823 # conjoin is a simple backtracking generator, named in honor of Icon's
1824 # "conjunction" control structure. Pass a list of no-argument functions
1825 # that return iterable objects. Easiest to explain by example: assume the
1826 # function list [x, y, z] is passed. Then conjoin acts like:
1827 #
1828 # def g():
1829 # values = [None] * 3
1830 # for values[0] in x():
1831 # for values[1] in y():
1832 # for values[2] in z():
1833 # yield values
1834 #
1835 # So some 3-lists of values *may* be generated, each time we successfully
1836 # get into the innermost loop. If an iterator fails (is exhausted) before
1837 # then, it "backtracks" to get the next value from the nearest enclosing
1838 # iterator (the one "to the left"), and starts all over again at the next
1839 # slot (pumps a fresh iterator). Of course this is most useful when the
1840 # iterators have side-effects, so that which values *can* be generated at
1841 # each slot depend on the values iterated at previous slots.
1842
1843 def simple_conjoin(gs):
1844
1845 values = [None] * len(gs)
1846
1847 def gen(i):
1848 if i >= len(gs):
1849 yield values
1850 else:
1851 for values[i] in gs[i]():
1852 for x in gen(i+1):
1853 yield x
1854
1855 for x in gen(0):
1856 yield x
1857
1858 # That works fine, but recursing a level and checking i against len(gs) for
1859 # each item produced is inefficient. By doing manual loop unrolling across
1860 # generator boundaries, it's possible to eliminate most of that overhead.
1861 # This isn't worth the bother *in general* for generators, but conjoin() is
1862 # a core building block for some CPU-intensive generator applications.
1863
1864 def conjoin(gs):
1865
1866 n = len(gs)
1867 values = [None] * n
1868
1869 # Do one loop nest at time recursively, until the # of loop nests
1870 # remaining is divisible by 3.
1871
1872 def gen(i):
1873 if i >= n:
1874 yield values
1875
1876 elif (n-i) % 3:
1877 ip1 = i+1
1878 for values[i] in gs[i]():
1879 for x in gen(ip1):
1880 yield x
1881
1882 else:
1883 for x in _gen3(i):
1884 yield x
1885
1886 # Do three loop nests at a time, recursing only if at least three more
1887 # remain. Don't call directly: this is an internal optimization for
1888 # gen's use.
1889
1890 def _gen3(i):
1891 assert i < n and (n-i) % 3 == 0
1892 ip1, ip2, ip3 = i+1, i+2, i+3
1893 g, g1, g2 = gs[i : ip3]
1894
1895 if ip3 >= n:
1896 # These are the last three, so we can yield values directly.
1897 for values[i] in g():
1898 for values[ip1] in g1():
1899 for values[ip2] in g2():
1900 yield values
1901
1902 else:
1903 # At least 6 loop nests remain; peel off 3 and recurse for the
1904 # rest.
1905 for values[i] in g():
1906 for values[ip1] in g1():
1907 for values[ip2] in g2():
1908 for x in _gen3(ip3):
1909 yield x
1910
1911 for x in gen(0):
1912 yield x
1913
1914 # And one more approach: For backtracking apps like the Knight's Tour
1915 # solver below, the number of backtracking levels can be enormous (one
1916 # level per square, for the Knight's Tour, so that e.g. a 100x100 board
1917 # needs 10,000 levels). In such cases Python is likely to run out of
1918 # stack space due to recursion. So here's a recursion-free version of
1919 # conjoin too.
1920 # NOTE WELL: This allows large problems to be solved with only trivial
1921 # demands on stack space. Without explicitly resumable generators, this is
1922 # much harder to achieve. OTOH, this is much slower (up to a factor of 2)
1923 # than the fancy unrolled recursive conjoin.
1924
1925 def flat_conjoin(gs): # rename to conjoin to run tests with this instead
1926 n = len(gs)
1927 values = [None] * n
1928 iters = [None] * n
1929 _StopIteration = StopIteration # make local because caught a *lot*
1930 i = 0
1931 while 1:
1932 # Descend.
1933 try:
1934 while i < n:
1935 it = iters[i] = gs[i]().__next__
1936 values[i] = it()
1937 i += 1
1938 except _StopIteration:
1939 pass
1940 else:
1941 assert i == n
1942 yield values
1943
1944 # Backtrack until an older iterator can be resumed.
1945 i -= 1
1946 while i >= 0:
1947 try:
1948 values[i] = iters[i]()
1949 # Success! Start fresh at next level.
1950 i += 1
1951 break
1952 except _StopIteration:
1953 # Continue backtracking.
1954 i -= 1
1955 else:
1956 assert i < 0
1957 break
1958
1959 # A conjoin-based N-Queens solver.
1960
1961 class Queens:
1962 def __init__(self, n):
1963 self.n = n
1964 rangen = range(n)
1965
1966 # Assign a unique int to each column and diagonal.
1967 # columns: n of those, range(n).
1968 # NW-SE diagonals: 2n-1 of these, i-j unique and invariant along
1969 # each, smallest i-j is 0-(n-1) = 1-n, so add n-1 to shift to 0-
1970 # based.
1971 # NE-SW diagonals: 2n-1 of these, i+j unique and invariant along
1972 # each, smallest i+j is 0, largest is 2n-2.
1973
1974 # For each square, compute a bit vector of the columns and
1975 # diagonals it covers, and for each row compute a function that
1976 # generates the possibilities for the columns in that row.
1977 self.rowgenerators = []
1978 for i in rangen:
1979 rowuses = [(1 << j) | # column ordinal
1980 (1 << (n + i-j + n-1)) | # NW-SE ordinal
1981 (1 << (n + 2*n-1 + i+j)) # NE-SW ordinal
1982 for j in rangen]
1983
1984 def rowgen(rowuses=rowuses):
1985 for j in rangen:
1986 uses = rowuses[j]
1987 if uses & self.used == 0:
1988 self.used |= uses
1989 yield j
1990 self.used &= ~uses
1991
1992 self.rowgenerators.append(rowgen)
1993
1994 # Generate solutions.
1995 def solve(self):
1996 self.used = 0
1997 for row2col in conjoin(self.rowgenerators):
1998 yield row2col
1999
2000 def printsolution(self, row2col):
2001 n = self.n
2002 assert n == len(row2col)
2003 sep = "+" + "-+" * n
2004 print(sep)
2005 for i in range(n):
2006 squares = [" " for j in range(n)]
2007 squares[row2col[i]] = "Q"
2008 print("|" + "|".join(squares) + "|")
2009 print(sep)
2010
2011 # A conjoin-based Knight's Tour solver. This is pretty sophisticated
2012 # (e.g., when used with flat_conjoin above, and passing hard=1 to the
2013 # constructor, a 200x200 Knight's Tour was found quickly -- note that we're
2014 # creating 10s of thousands of generators then!), and is lengthy.
2015
2016 class Knights:
2017 def __init__(self, m, n, hard=0):
2018 self.m, self.n = m, n
2019
2020 # solve() will set up succs[i] to be a list of square #i's
2021 # successors.
2022 succs = self.succs = []
2023
2024 # Remove i0 from each of its successor's successor lists, i.e.
2025 # successors can't go back to i0 again. Return 0 if we can
2026 # detect this makes a solution impossible, else return 1.
2027
2028 def remove_from_successors(i0, len=len):
2029 # If we remove all exits from a free square, we're dead:
2030 # even if we move to it next, we can't leave it again.
2031 # If we create a square with one exit, we must visit it next;
2032 # else somebody else will have to visit it, and since there's
2033 # only one adjacent, there won't be a way to leave it again.
2034 # Finally, if we create more than one free square with a
2035 # single exit, we can only move to one of them next, leaving
2036 # the other one a dead end.
2037 ne0 = ne1 = 0
2038 for i in succs[i0]:
2039 s = succs[i]
2040 s.remove(i0)
2041 e = len(s)
2042 if e == 0:
2043 ne0 += 1
2044 elif e == 1:
2045 ne1 += 1
2046 return ne0 == 0 and ne1 < 2
2047
2048 # Put i0 back in each of its successor's successor lists.
2049
2050 def add_to_successors(i0):
2051 for i in succs[i0]:
2052 succs[i].append(i0)
2053
2054 # Generate the first move.
2055 def first():
2056 if m < 1 or n < 1:
2057 return
2058
2059 # Since we're looking for a cycle, it doesn't matter where we
2060 # start. Starting in a corner makes the 2nd move easy.
2061 corner = self.coords2index(0, 0)
2062 remove_from_successors(corner)
2063 self.lastij = corner
2064 yield corner
2065 add_to_successors(corner)
2066
2067 # Generate the second moves.
2068 def second():
2069 corner = self.coords2index(0, 0)
2070 assert self.lastij == corner # i.e., we started in the corner
2071 if m < 3 or n < 3:
2072 return
2073 assert len(succs[corner]) == 2
2074 assert self.coords2index(1, 2) in succs[corner]
2075 assert self.coords2index(2, 1) in succs[corner]
2076 # Only two choices. Whichever we pick, the other must be the
2077 # square picked on move m*n, as it's the only way to get back
2078 # to (0, 0). Save its index in self.final so that moves before
2079 # the last know it must be kept free.
2080 for i, j in (1, 2), (2, 1):
2081 this = self.coords2index(i, j)
2082 final = self.coords2index(3-i, 3-j)
2083 self.final = final
2084
2085 remove_from_successors(this)
2086 succs[final].append(corner)
2087 self.lastij = this
2088 yield this
2089 succs[final].remove(corner)
2090 add_to_successors(this)
2091
2092 # Generate moves 3 through m*n-1.
2093 def advance(len=len):
2094 # If some successor has only one exit, must take it.
2095 # Else favor successors with fewer exits.
2096 candidates = []
2097 for i in succs[self.lastij]:
2098 e = len(succs[i])
2099 assert e > 0, "else remove_from_successors() pruning flawed"
2100 if e == 1:
2101 candidates = [(e, i)]
2102 break
2103 candidates.append((e, i))
2104 else:
2105 candidates.sort()
2106
2107 for e, i in candidates:
2108 if i != self.final:
2109 if remove_from_successors(i):
2110 self.lastij = i
2111 yield i
2112 add_to_successors(i)
2113
2114 # Generate moves 3 through m*n-1. Alternative version using a
2115 # stronger (but more expensive) heuristic to order successors.
2116 # Since the # of backtracking levels is m*n, a poor move early on
2117 # can take eons to undo. Smallest square board for which this
2118 # matters a lot is 52x52.
2119 def advance_hard(vmid=(m-1)/2.0, hmid=(n-1)/2.0, len=len):
2120 # If some successor has only one exit, must take it.
2121 # Else favor successors with fewer exits.
2122 # Break ties via max distance from board centerpoint (favor
2123 # corners and edges whenever possible).
2124 candidates = []
2125 for i in succs[self.lastij]:
2126 e = len(succs[i])
2127 assert e > 0, "else remove_from_successors() pruning flawed"
2128 if e == 1:
2129 candidates = [(e, 0, i)]
2130 break
2131 i1, j1 = self.index2coords(i)
2132 d = (i1 - vmid)**2 + (j1 - hmid)**2
2133 candidates.append((e, -d, i))
2134 else:
2135 candidates.sort()
2136
2137 for e, d, i in candidates:
2138 if i != self.final:
2139 if remove_from_successors(i):
2140 self.lastij = i
2141 yield i
2142 add_to_successors(i)
2143
2144 # Generate the last move.
2145 def last():
2146 assert self.final in succs[self.lastij]
2147 yield self.final
2148
2149 if m*n < 4:
2150 self.squaregenerators = [first]
2151 else:
2152 self.squaregenerators = [first, second] + \
2153 [hard and advance_hard or advance] * (m*n - 3) + \
2154 [last]
2155
2156 def coords2index(self, i, j):
2157 assert 0 <= i < self.m
2158 assert 0 <= j < self.n
2159 return i * self.n + j
2160
2161 def index2coords(self, index):
2162 assert 0 <= index < self.m * self.n
2163 return divmod(index, self.n)
2164
2165 def _init_board(self):
2166 succs = self.succs
2167 del succs[:]
2168 m, n = self.m, self.n
2169 c2i = self.coords2index
2170
2171 offsets = [( 1, 2), ( 2, 1), ( 2, -1), ( 1, -2),
2172 (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
2173 rangen = range(n)
2174 for i in range(m):
2175 for j in rangen:
2176 s = [c2i(i+io, j+jo) for io, jo in offsets
2177 if 0 <= i+io < m and
2178 0 <= j+jo < n]
2179 succs.append(s)
2180
2181 # Generate solutions.
2182 def solve(self):
2183 self._init_board()
2184 for x in conjoin(self.squaregenerators):
2185 yield x
2186
2187 def printsolution(self, x):
2188 m, n = self.m, self.n
2189 assert len(x) == m*n
2190 w = len(str(m*n))
2191 format = "%" + str(w) + "d"
2192
2193 squares = [[None] * n for i in range(m)]
2194 k = 1
2195 for i in x:
2196 i1, j1 = self.index2coords(i)
2197 squares[i1][j1] = format % k
2198 k += 1
2199
2200 sep = "+" + ("-" * w + "+") * n
2201 print(sep)
2202 for i in range(m):
2203 row = squares[i]
2204 print("|" + "|".join(row) + "|")
2205 print(sep)
2206
2207 conjoin_tests = """
2208
2209 Generate the 3-bit binary numbers in order. This illustrates dumbest-
2210 possible use of conjoin, just to generate the full cross-product.
2211
2212 >>> for c in conjoin([lambda: iter((0, 1))] * 3):
2213 ... print(c)
2214 [0, 0, 0]
2215 [0, 0, 1]
2216 [0, 1, 0]
2217 [0, 1, 1]
2218 [1, 0, 0]
2219 [1, 0, 1]
2220 [1, 1, 0]
2221 [1, 1, 1]
2222
2223 For efficiency in typical backtracking apps, conjoin() yields the same list
2224 object each time. So if you want to save away a full account of its
2225 generated sequence, you need to copy its results.
2226
2227 >>> def gencopy(iterator):
2228 ... for x in iterator:
2229 ... yield x[:]
2230
2231 >>> for n in range(10):
2232 ... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n)))
2233 ... print(n, len(all), all[0] == [0] * n, all[-1] == [1] * n)
2234 0 1 True True
2235 1 2 True True
2236 2 4 True True
2237 3 8 True True
2238 4 16 True True
2239 5 32 True True
2240 6 64 True True
2241 7 128 True True
2242 8 256 True True
2243 9 512 True True
2244
2245 And run an 8-queens solver.
2246
2247 >>> q = Queens(8)
2248 >>> LIMIT = 2
2249 >>> count = 0
2250 >>> for row2col in q.solve():
2251 ... count += 1
2252 ... if count <= LIMIT:
2253 ... print("Solution", count)
2254 ... q.printsolution(row2col)
2255 Solution 1
2256 +-+-+-+-+-+-+-+-+
2257 |Q| | | | | | | |
2258 +-+-+-+-+-+-+-+-+
2259 | | | | |Q| | | |
2260 +-+-+-+-+-+-+-+-+
2261 | | | | | | | |Q|
2262 +-+-+-+-+-+-+-+-+
2263 | | | | | |Q| | |
2264 +-+-+-+-+-+-+-+-+
2265 | | |Q| | | | | |
2266 +-+-+-+-+-+-+-+-+
2267 | | | | | | |Q| |
2268 +-+-+-+-+-+-+-+-+
2269 | |Q| | | | | | |
2270 +-+-+-+-+-+-+-+-+
2271 | | | |Q| | | | |
2272 +-+-+-+-+-+-+-+-+
2273 Solution 2
2274 +-+-+-+-+-+-+-+-+
2275 |Q| | | | | | | |
2276 +-+-+-+-+-+-+-+-+
2277 | | | | | |Q| | |
2278 +-+-+-+-+-+-+-+-+
2279 | | | | | | | |Q|
2280 +-+-+-+-+-+-+-+-+
2281 | | |Q| | | | | |
2282 +-+-+-+-+-+-+-+-+
2283 | | | | | | |Q| |
2284 +-+-+-+-+-+-+-+-+
2285 | | | |Q| | | | |
2286 +-+-+-+-+-+-+-+-+
2287 | |Q| | | | | | |
2288 +-+-+-+-+-+-+-+-+
2289 | | | | |Q| | | |
2290 +-+-+-+-+-+-+-+-+
2291
2292 >>> print(count, "solutions in all.")
2293 92 solutions in all.
2294
2295 And run a Knight's Tour on a 10x10 board. Note that there are about
2296 20,000 solutions even on a 6x6 board, so don't dare run this to exhaustion.
2297
2298 >>> k = Knights(10, 10)
2299 >>> LIMIT = 2
2300 >>> count = 0
2301 >>> for x in k.solve():
2302 ... count += 1
2303 ... if count <= LIMIT:
2304 ... print("Solution", count)
2305 ... k.printsolution(x)
2306 ... else:
2307 ... break
2308 Solution 1
2309 +---+---+---+---+---+---+---+---+---+---+
2310 | 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
2311 +---+---+---+---+---+---+---+---+---+---+
2312 | 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
2313 +---+---+---+---+---+---+---+---+---+---+
2314 | 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
2315 +---+---+---+---+---+---+---+---+---+---+
2316 | 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
2317 +---+---+---+---+---+---+---+---+---+---+
2318 | 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
2319 +---+---+---+---+---+---+---+---+---+---+
2320 | 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
2321 +---+---+---+---+---+---+---+---+---+---+
2322 | 87| 98| 91| 80| 77| 84| 53| 46| 65| 44|
2323 +---+---+---+---+---+---+---+---+---+---+
2324 | 90| 23| 88| 95| 70| 79| 68| 83| 14| 17|
2325 +---+---+---+---+---+---+---+---+---+---+
2326 | 97| 92| 21| 78| 81| 94| 19| 16| 45| 66|
2327 +---+---+---+---+---+---+---+---+---+---+
2328 | 22| 89| 96| 93| 20| 69| 82| 67| 18| 15|
2329 +---+---+---+---+---+---+---+---+---+---+
2330 Solution 2
2331 +---+---+---+---+---+---+---+---+---+---+
2332 | 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
2333 +---+---+---+---+---+---+---+---+---+---+
2334 | 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
2335 +---+---+---+---+---+---+---+---+---+---+
2336 | 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
2337 +---+---+---+---+---+---+---+---+---+---+
2338 | 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
2339 +---+---+---+---+---+---+---+---+---+---+
2340 | 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
2341 +---+---+---+---+---+---+---+---+---+---+
2342 | 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
2343 +---+---+---+---+---+---+---+---+---+---+
2344 | 87| 98| 89| 80| 77| 84| 53| 46| 65| 44|
2345 +---+---+---+---+---+---+---+---+---+---+
2346 | 90| 23| 92| 95| 70| 79| 68| 83| 14| 17|
2347 +---+---+---+---+---+---+---+---+---+---+
2348 | 97| 88| 21| 78| 81| 94| 19| 16| 45| 66|
2349 +---+---+---+---+---+---+---+---+---+---+
2350 | 22| 91| 96| 93| 20| 69| 82| 67| 18| 15|
2351 +---+---+---+---+---+---+---+---+---+---+
2352 """
2353
2354 weakref_tests = """\
2355 Generators are weakly referencable:
2356
2357 >>> import weakref
2358 >>> def gen():
2359 ... yield 'foo!'
2360 ...
2361 >>> wr = weakref.ref(gen)
2362 >>> wr() is gen
2363 True
2364 >>> p = weakref.proxy(gen)
2365
2366 Generator-iterators are weakly referencable as well:
2367
2368 >>> gi = gen()
2369 >>> wr = weakref.ref(gi)
2370 >>> wr() is gi
2371 True
2372 >>> p = weakref.proxy(gi)
2373 >>> list(p)
2374 ['foo!']
2375
2376 """
2377
2378 coroutine_tests = """\
2379 >>> from test.support import gc_collect
2380
2381 Sending a value into a started generator:
2382
2383 >>> def f():
2384 ... print((yield 1))
2385 ... yield 2
2386 >>> g = f()
2387 >>> next(g)
2388 1
2389 >>> g.send(42)
2390 42
2391 2
2392
2393 Sending a value into a new generator produces a TypeError:
2394
2395 >>> f().send("foo")
2396 Traceback (most recent call last):
2397 ...
2398 TypeError: can't send non-None value to a just-started generator
2399
2400
2401 Yield by itself yields None:
2402
2403 >>> def f(): yield
2404 >>> list(f())
2405 [None]
2406
2407
2408 Yield is allowed only in the outermost iterable in generator expression:
2409
2410 >>> def f(): list(i for i in [(yield 26)])
2411 >>> type(f())
2412 <class 'generator'>
2413
2414
2415 A yield expression with augmented assignment.
2416
2417 >>> def coroutine(seq):
2418 ... count = 0
2419 ... while count < 200:
2420 ... count += yield
2421 ... seq.append(count)
2422 >>> seq = []
2423 >>> c = coroutine(seq)
2424 >>> next(c)
2425 >>> print(seq)
2426 []
2427 >>> c.send(10)
2428 >>> print(seq)
2429 [10]
2430 >>> c.send(10)
2431 >>> print(seq)
2432 [10, 20]
2433 >>> c.send(10)
2434 >>> print(seq)
2435 [10, 20, 30]
2436
2437
2438 Check some syntax errors for yield expressions:
2439
2440 >>> f=lambda: (yield 1),(yield 2)
2441 Traceback (most recent call last):
2442 ...
2443 SyntaxError: 'yield' outside function
2444
2445 >>> f=lambda: (yield from (1,2)), (yield from (3,4))
2446 Traceback (most recent call last):
2447 ...
2448 SyntaxError: 'yield from' outside function
2449
2450 >>> yield from [1,2]
2451 Traceback (most recent call last):
2452 ...
2453 SyntaxError: 'yield from' outside function
2454
2455 >>> def f(): x = yield = y
2456 Traceback (most recent call last):
2457 ...
2458 SyntaxError: assignment to yield expression not possible
2459
2460 >>> def f(): (yield bar) = y
2461 Traceback (most recent call last):
2462 ...
2463 SyntaxError: cannot assign to yield expression here. Maybe you meant '==' instead of '='?
2464
2465 >>> def f(): (yield bar) += y
2466 Traceback (most recent call last):
2467 ...
2468 SyntaxError: 'yield expression' is an illegal expression for augmented assignment
2469
2470
2471 Now check some throw() conditions:
2472
2473 >>> def f():
2474 ... while True:
2475 ... try:
2476 ... print((yield))
2477 ... except ValueError as v:
2478 ... print("caught ValueError (%s)" % (v))
2479 >>> import sys
2480 >>> g = f()
2481 >>> next(g)
2482
2483 >>> g.throw(ValueError) # type only
2484 caught ValueError ()
2485
2486 >>> g.throw(ValueError("xyz")) # value only
2487 caught ValueError (xyz)
2488
2489 >>> import warnings
2490 >>> old_filters = warnings.filters.copy()
2491 >>> warnings.filterwarnings("ignore", category=DeprecationWarning)
2492
2493 # Filter DeprecationWarning: regarding the (type, val, tb) signature of throw().
2494 # Deprecation warnings are re-enabled below.
2495
2496 >>> g.throw(ValueError, ValueError(1)) # value+matching type
2497 caught ValueError (1)
2498
2499 >>> g.throw(ValueError, TypeError(1)) # mismatched type, rewrapped
2500 caught ValueError (1)
2501
2502 >>> g.throw(ValueError, ValueError(1), None) # explicit None traceback
2503 caught ValueError (1)
2504
2505 >>> g.throw(ValueError(1), "foo") # bad args
2506 Traceback (most recent call last):
2507 ...
2508 TypeError: instance exception may not have a separate value
2509
2510 >>> g.throw(ValueError, "foo", 23) # bad args
2511 Traceback (most recent call last):
2512 ...
2513 TypeError: throw() third argument must be a traceback object
2514
2515 >>> g.throw("abc")
2516 Traceback (most recent call last):
2517 ...
2518 TypeError: exceptions must be classes or instances deriving from BaseException, not str
2519
2520 >>> g.throw(0)
2521 Traceback (most recent call last):
2522 ...
2523 TypeError: exceptions must be classes or instances deriving from BaseException, not int
2524
2525 >>> g.throw(list)
2526 Traceback (most recent call last):
2527 ...
2528 TypeError: exceptions must be classes or instances deriving from BaseException, not type
2529
2530 >>> def throw(g,exc):
2531 ... try:
2532 ... raise exc
2533 ... except:
2534 ... g.throw(*sys.exc_info())
2535 >>> throw(g,ValueError) # do it with traceback included
2536 caught ValueError ()
2537
2538 >>> g.send(1)
2539 1
2540
2541 >>> throw(g,TypeError) # terminate the generator
2542 Traceback (most recent call last):
2543 ...
2544 TypeError
2545
2546 >>> print(g.gi_frame)
2547 None
2548
2549 >>> g.send(2)
2550 Traceback (most recent call last):
2551 ...
2552 StopIteration
2553
2554 >>> g.throw(ValueError,6) # throw on closed generator
2555 Traceback (most recent call last):
2556 ...
2557 ValueError: 6
2558
2559 >>> f().throw(ValueError,7) # throw on just-opened generator
2560 Traceback (most recent call last):
2561 ...
2562 ValueError: 7
2563
2564 >>> warnings.filters[:] = old_filters
2565
2566 # Re-enable DeprecationWarning: the (type, val, tb) exception representation is deprecated,
2567 # and may be removed in a future version of Python.
2568
2569 Plain "raise" inside a generator should preserve the traceback (#13188).
2570 The traceback should have 3 levels:
2571 - g.throw()
2572 - f()
2573 - 1/0
2574
2575 >>> def f():
2576 ... try:
2577 ... yield
2578 ... except:
2579 ... raise
2580 >>> g = f()
2581 >>> try:
2582 ... 1/0
2583 ... except ZeroDivisionError as v:
2584 ... try:
2585 ... g.throw(v)
2586 ... except Exception as w:
2587 ... tb = w.__traceback__
2588 >>> levels = 0
2589 >>> while tb:
2590 ... levels += 1
2591 ... tb = tb.tb_next
2592 >>> levels
2593 3
2594
2595 Now let's try closing a generator:
2596
2597 >>> def f():
2598 ... try: yield
2599 ... except GeneratorExit:
2600 ... print("exiting")
2601
2602 >>> g = f()
2603 >>> next(g)
2604 >>> g.close()
2605 exiting
2606 >>> g.close() # should be no-op now
2607
2608 >>> f().close() # close on just-opened generator should be fine
2609
2610 >>> def f(): yield # an even simpler generator
2611 >>> f().close() # close before opening
2612 >>> g = f()
2613 >>> next(g)
2614 >>> g.close() # close normally
2615
2616 And finalization:
2617
2618 >>> def f():
2619 ... try: yield
2620 ... finally:
2621 ... print("exiting")
2622
2623 >>> g = f()
2624 >>> next(g)
2625 >>> del g; gc_collect() # For PyPy or other GCs.
2626 exiting
2627
2628
2629 GeneratorExit is not caught by except Exception:
2630
2631 >>> def f():
2632 ... try: yield
2633 ... except Exception:
2634 ... print('except')
2635 ... finally:
2636 ... print('finally')
2637
2638 >>> g = f()
2639 >>> next(g)
2640 >>> del g; gc_collect() # For PyPy or other GCs.
2641 finally
2642
2643
2644 Now let's try some ill-behaved generators:
2645
2646 >>> def f():
2647 ... try: yield
2648 ... except GeneratorExit:
2649 ... yield "foo!"
2650 >>> g = f()
2651 >>> next(g)
2652 >>> g.close()
2653 Traceback (most recent call last):
2654 ...
2655 RuntimeError: generator ignored GeneratorExit
2656 >>> g.close()
2657
2658
2659 Our ill-behaved code should be invoked during GC:
2660
2661 >>> with support.catch_unraisable_exception() as cm:
2662 ... g = f()
2663 ... next(g)
2664 ... del g
2665 ...
2666 ... cm.unraisable.exc_type == RuntimeError
2667 ... "generator ignored GeneratorExit" in str(cm.unraisable.exc_value)
2668 ... cm.unraisable.exc_traceback is not None
2669 True
2670 True
2671 True
2672
2673 And errors thrown during closing should propagate:
2674
2675 >>> def f():
2676 ... try: yield
2677 ... except GeneratorExit:
2678 ... raise TypeError("fie!")
2679 >>> g = f()
2680 >>> next(g)
2681 >>> g.close()
2682 Traceback (most recent call last):
2683 ...
2684 TypeError: fie!
2685
2686
2687 Ensure that various yield expression constructs make their
2688 enclosing function a generator:
2689
2690 >>> def f(): x += yield
2691 >>> type(f())
2692 <class 'generator'>
2693
2694 >>> def f(): x = yield
2695 >>> type(f())
2696 <class 'generator'>
2697
2698 >>> def f(): lambda x=(yield): 1
2699 >>> type(f())
2700 <class 'generator'>
2701
2702 >>> def f(d): d[(yield "a")] = d[(yield "b")] = 27
2703 >>> data = [1,2]
2704 >>> g = f(data)
2705 >>> type(g)
2706 <class 'generator'>
2707 >>> g.send(None)
2708 'a'
2709 >>> data
2710 [1, 2]
2711 >>> g.send(0)
2712 'b'
2713 >>> data
2714 [27, 2]
2715 >>> try: g.send(1)
2716 ... except StopIteration: pass
2717 >>> data
2718 [27, 27]
2719
2720 """
2721
2722 refleaks_tests = """
2723 Prior to adding cycle-GC support to itertools.tee, this code would leak
2724 references. We add it to the standard suite so the routine refleak-tests
2725 would trigger if it starts being uncleanable again.
2726
2727 >>> import itertools
2728 >>> def leak():
2729 ... class gen:
2730 ... def __iter__(self):
2731 ... return self
2732 ... def __next__(self):
2733 ... return self.item
2734 ... g = gen()
2735 ... head, tail = itertools.tee(g)
2736 ... g.item = head
2737 ... return head
2738 >>> it = leak()
2739
2740 Make sure to also test the involvement of the tee-internal teedataobject,
2741 which stores returned items.
2742
2743 >>> item = next(it)
2744
2745
2746
2747 This test leaked at one point due to generator finalization/destruction.
2748 It was copied from Lib/test/leakers/test_generator_cycle.py before the file
2749 was removed.
2750
2751 >>> def leak():
2752 ... def gen():
2753 ... while True:
2754 ... yield g
2755 ... g = gen()
2756
2757 >>> leak()
2758
2759
2760
2761 This test isn't really generator related, but rather exception-in-cleanup
2762 related. The coroutine tests (above) just happen to cause an exception in
2763 the generator's __del__ (tp_del) method. We can also test for this
2764 explicitly, without generators. We do have to redirect stderr to avoid
2765 printing warnings and to doublecheck that we actually tested what we wanted
2766 to test.
2767
2768 >>> from test import support
2769 >>> class Leaker:
2770 ... def __del__(self):
2771 ... def invoke(message):
2772 ... raise RuntimeError(message)
2773 ... invoke("del failed")
2774 ...
2775 >>> with support.catch_unraisable_exception() as cm:
2776 ... l = Leaker()
2777 ... del l
2778 ...
2779 ... cm.unraisable.object == Leaker.__del__
2780 ... cm.unraisable.exc_type == RuntimeError
2781 ... str(cm.unraisable.exc_value) == "del failed"
2782 ... cm.unraisable.exc_traceback is not None
2783 True
2784 True
2785 True
2786 True
2787
2788
2789 These refleak tests should perhaps be in a testfile of their own,
2790 test_generators just happened to be the test that drew these out.
2791
2792 """
2793
2794 __test__ = {"tut": tutorial_tests,
2795 "pep": pep_tests,
2796 "email": email_tests,
2797 "fun": fun_tests,
2798 "syntax": syntax_tests,
2799 "conjoin": conjoin_tests,
2800 "weakref": weakref_tests,
2801 "coroutine": coroutine_tests,
2802 "refleaks": refleaks_tests,
2803 }
2804
2805 def load_tests(loader, tests, pattern):
2806 tests.addTest(doctest.DocTestSuite())
2807 return tests
2808
2809
2810 if __name__ == "__main__":
2811 unittest.main()