Debian Codegraph @

lib-python/3/test/test_generators.py

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