ronnie
2022-10-14 1504bb53e29d3d46222c0b3ea994fc494b48e153
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
P\¬Qc@sådZdZdZdZdZd„Zd„Zd„Zdfd    „ƒYZd
fd „ƒYZ    d Z
d Z dZ dZ i    ed6ed6ed6ed6ed6e
d6e d6e d6e d6Zed„ZedkráedƒndS(sÜ    
Let's try a simple generator:
 
    >>> def f():
    ...    yield 1
    ...    yield 2
 
    >>> for i in f():
    ...     print i
    1
    2
    >>> g = f()
    >>> g.next()
    1
    >>> g.next()
    2
 
"Falling off the end" stops the generator:
 
    >>> g.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<stdin>", line 2, in g
    StopIteration
 
"return" also stops the generator:
 
    >>> def f():
    ...     yield 1
    ...     return
    ...     yield 2 # never reached
    ...
    >>> g = f()
    >>> g.next()
    1
    >>> g.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<stdin>", line 3, in f
    StopIteration
    >>> g.next() # once stopped, can't be resumed
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    StopIteration
 
"raise StopIteration" stops the generator too:
 
    >>> def f():
    ...     yield 1
    ...     raise StopIteration
    ...     yield 2 # never reached
    ...
    >>> g = f()
    >>> g.next()
    1
    >>> g.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    StopIteration
    >>> g.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    StopIteration
 
However, they are not exactly equivalent:
 
    >>> def g1():
    ...     try:
    ...         return
    ...     except:
    ...         yield 1
    ...
    >>> list(g1())
    []
 
    >>> def g2():
    ...     try:
    ...         raise StopIteration
    ...     except:
    ...         yield 42
    >>> print list(g2())
    [42]
 
This may be surprising at first:
 
    >>> def g3():
    ...     try:
    ...         return
    ...     finally:
    ...         yield 1
    ...
    >>> list(g3())
    [1]
 
Let's create an alternate range() function implemented as a generator:
 
    >>> def yrange(n):
    ...     for i in range(n):
    ...         yield i
    ...
    >>> list(yrange(5))
    [0, 1, 2, 3, 4]
 
Generators always return to the most recent caller:
 
    >>> def creator():
    ...     r = yrange(5)
    ...     print "creator", r.next()
    ...     return r
    ...
    >>> def caller():
    ...     r = creator()
    ...     for i in r:
    ...             print "caller", i
    ...
    >>> caller()
    creator 0
    caller 1
    caller 2
    caller 3
    caller 4
 
Generators can call other generators:
 
    >>> def zrange(n):
    ...     for i in yrange(n):
    ...         yield i
    ...
    >>> list(zrange(5))
    [0, 1, 2, 3, 4]
 
sq
 
Specification:  Yield
 
    Restriction:  A generator cannot be resumed while it is actively
    running:
 
    >>> def g():
    ...     i = me.next()
    ...     yield i
    >>> me = g()
    >>> me.next()
    Traceback (most recent call last):
     ...
      File "<string>", line 2, in g
    ValueError: generator already executing
 
Specification: Return
 
    Note that return isn't always equivalent to raising StopIteration:  the
    difference lies in how enclosing try/except constructs are treated.
    For example,
 
        >>> def f1():
        ...     try:
        ...         return
        ...     except:
        ...        yield 1
        >>> print list(f1())
        []
 
    because, as in any function, return simply exits, but
 
        >>> def f2():
        ...     try:
        ...         raise StopIteration
        ...     except:
        ...         yield 42
        >>> print list(f2())
        [42]
 
    because StopIteration is captured by a bare "except", as is any
    exception.
 
Specification: Generators and Exception Propagation
 
    >>> def f():
    ...     return 1//0
    >>> def g():
    ...     yield f()  # the zero division exception propagates
    ...     yield 42   # and we'll never get here
    >>> k = g()
    >>> k.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<stdin>", line 2, in g
      File "<stdin>", line 2, in f
    ZeroDivisionError: integer division or modulo by zero
    >>> k.next()  # and the generator cannot be resumed
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    StopIteration
    >>>
 
Specification: Try/Except/Finally
 
    >>> def f():
    ...     try:
    ...         yield 1
    ...         try:
    ...             yield 2
    ...             1//0
    ...             yield 3  # never get here
    ...         except ZeroDivisionError:
    ...             yield 4
    ...             yield 5
    ...             raise
    ...         except:
    ...             yield 6
    ...         yield 7     # the "raise" above stops this
    ...     except:
    ...         yield 8
    ...     yield 9
    ...     try:
    ...         x = 12
    ...     finally:
    ...         yield 10
    ...     yield 11
    >>> print list(f())
    [1, 2, 4, 5, 8, 9, 10, 11]
    >>>
 
Guido's binary tree example.
 
    >>> # A binary tree class.
    >>> class Tree:
    ...
    ...     def __init__(self, label, left=None, right=None):
    ...         self.label = label
    ...         self.left = left
    ...         self.right = right
    ...
    ...     def __repr__(self, level=0, indent="    "):
    ...         s = level*indent + repr(self.label)
    ...         if self.left:
    ...             s = s + "\n" + self.left.__repr__(level+1, indent)
    ...         if self.right:
    ...             s = s + "\n" + self.right.__repr__(level+1, indent)
    ...         return s
    ...
    ...     def __iter__(self):
    ...         return inorder(self)
 
    >>> # Create a Tree from a list.
    >>> def tree(list):
    ...     n = len(list)
    ...     if n == 0:
    ...         return []
    ...     i = n // 2
    ...     return Tree(list[i], tree(list[:i]), tree(list[i+1:]))
 
    >>> # Show it off: create a tree.
    >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
 
    >>> # A recursive generator that generates Tree labels in in-order.
    >>> def inorder(t):
    ...     if t:
    ...         for x in inorder(t.left):
    ...             yield x
    ...         yield t.label
    ...         for x in inorder(t.right):
    ...             yield x
 
    >>> # Show it off: create a tree.
    >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    >>> # Print the nodes of the tree in in-order.
    >>> for x in t:
    ...     print x,
    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
 
    >>> # A non-recursive generator.
    >>> def inorder(node):
    ...     stack = []
    ...     while node:
    ...         while node.left:
    ...             stack.append(node)
    ...             node = node.left
    ...         yield node.label
    ...         while not node.right:
    ...             try:
    ...                 node = stack.pop()
    ...             except IndexError:
    ...                 return
    ...             yield node.label
    ...         node = node.right
 
    >>> # Exercise the non-recursive generator.
    >>> for x in t:
    ...     print x,
    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
 
sY
 
The difference between yielding None and returning it.
 
>>> def g():
...     for i in range(3):
...         yield None
...     yield None
...     return
>>> list(g())
[None, None, None, None]
 
Ensure that explicitly raising StopIteration acts like any other exception
in try/except, not like a return.
 
>>> def g():
...     yield 1
...     try:
...         raise StopIteration
...     except:
...         yield 2
...     yield 3
>>> list(g())
[1, 2, 3]
 
Next one was posted to c.l.py.
 
>>> def gcomb(x, k):
...     "Generate all combinations of k elements from list x."
...
...     if k > len(x):
...         return
...     if k == 0:
...         yield []
...     else:
...         first, rest = x[0], x[1:]
...         # A combination does or doesn't contain first.
...         # If it does, the remainder is a k-1 comb of rest.
...         for c in gcomb(rest, k-1):
...             c.insert(0, first)
...             yield c
...         # If it doesn't contain first, it's a k comb of rest.
...         for c in gcomb(rest, k):
...             yield c
 
>>> seq = range(1, 5)
>>> for k in range(len(seq) + 2):
...     print "%d-combs of %s:" % (k, seq)
...     for c in gcomb(seq, k):
...         print "   ", c
0-combs of [1, 2, 3, 4]:
    []
1-combs of [1, 2, 3, 4]:
    [1]
    [2]
    [3]
    [4]
2-combs of [1, 2, 3, 4]:
    [1, 2]
    [1, 3]
    [1, 4]
    [2, 3]
    [2, 4]
    [3, 4]
3-combs of [1, 2, 3, 4]:
    [1, 2, 3]
    [1, 2, 4]
    [1, 3, 4]
    [2, 3, 4]
4-combs of [1, 2, 3, 4]:
    [1, 2, 3, 4]
5-combs of [1, 2, 3, 4]:
 
From the Iterators list, about the types of these things.
 
>>> def g():
...     yield 1
...
>>> type(g)
<type 'function'>
>>> i = g()
>>> type(i)
<type 'generator'>
>>> [s for s in dir(i) if not s.startswith('_')]
['close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw']
>>> from test.test_support import HAVE_DOCSTRINGS
>>> print(i.next.__doc__ if HAVE_DOCSTRINGS else 'x.next() -> the next value, or raise StopIteration')
x.next() -> the next value, or raise StopIteration
>>> iter(i) is i
True
>>> import types
>>> isinstance(i, types.GeneratorType)
True
 
And more, added later.
 
>>> i.gi_running
0
>>> type(i.gi_frame)
<type 'frame'>
>>> i.gi_running = 42
Traceback (most recent call last):
  ...
TypeError: readonly attribute
>>> def g():
...     yield me.gi_running
>>> me = g()
>>> me.gi_running
0
>>> me.next()
1
>>> me.gi_running
0
 
A clever union-find implementation from c.l.py, due to David Eppstein.
Sent: Friday, June 29, 2001 12:16 PM
To: python-list@python.org
Subject: Re: PEP 255: Simple Generators
 
>>> class disjointSet:
...     def __init__(self, name):
...         self.name = name
...         self.parent = None
...         self.generator = self.generate()
...
...     def generate(self):
...         while not self.parent:
...             yield self
...         for x in self.parent.generator:
...             yield x
...
...     def find(self):
...         return self.generator.next()
...
...     def union(self, parent):
...         if self.parent:
...             raise ValueError("Sorry, I'm not a root!")
...         self.parent = parent
...
...     def __str__(self):
...         return self.name
 
>>> names = "ABCDEFGHIJKLM"
>>> sets = [disjointSet(name) for name in names]
>>> roots = sets[:]
 
>>> import random
>>> gen = random.WichmannHill(42)
>>> while 1:
...     for s in sets:
...         print "%s->%s" % (s, s.find()),
...     print
...     if len(roots) > 1:
...         s1 = gen.choice(roots)
...         roots.remove(s1)
...         s2 = gen.choice(roots)
...         s1.union(s2)
...         print "merged", s1, "into", s2
...     else:
...         break
A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M
merged D into G
A->A B->B C->C D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M
merged C into F
A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M
merged L into A
A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->A M->M
merged H into E
A->A B->B C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M
merged B into E
A->A B->E C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M
merged J into G
A->A B->E C->F D->G E->E F->F G->G H->E I->I J->G K->K L->A M->M
merged E into G
A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->M
merged M into G
A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->G
merged I into K
A->A B->G C->F D->G E->G F->F G->G H->G I->K J->G K->K L->A M->G
merged K into A
A->A B->G C->F D->G E->G F->F G->G H->G I->A J->G K->A L->A M->G
merged F into A
A->A B->G C->A D->G E->G F->A G->G H->G I->A J->G K->A L->A M->G
merged A into G
A->G B->G C->G D->G E->G F->G G->G H->G I->G J->G K->G L->G M->G
 
sª
 
Build up to a recursive Sieve of Eratosthenes generator.
 
>>> def firstn(g, n):
...     return [g.next() for i in range(n)]
 
>>> def intsfrom(i):
...     while 1:
...         yield i
...         i += 1
 
>>> firstn(intsfrom(5), 7)
[5, 6, 7, 8, 9, 10, 11]
 
>>> def exclude_multiples(n, ints):
...     for i in ints:
...         if i % n:
...             yield i
 
>>> firstn(exclude_multiples(3, intsfrom(1)), 6)
[1, 2, 4, 5, 7, 8]
 
>>> def sieve(ints):
...     prime = ints.next()
...     yield prime
...     not_divisible_by_prime = exclude_multiples(prime, ints)
...     for p in sieve(not_divisible_by_prime):
...         yield p
 
>>> primes = sieve(intsfrom(2))
>>> firstn(primes, 20)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
 
 
Another famous problem:  generate all integers of the form
    2**i * 3**j  * 5**k
in increasing order, where i,j,k >= 0.  Trickier than it may look at first!
Try writing it without generators, and correctly, and without generating
3 internal results for each result output.
 
>>> def times(n, g):
...     for i in g:
...         yield n * i
>>> firstn(times(10, intsfrom(1)), 10)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
 
>>> def merge(g, h):
...     ng = g.next()
...     nh = h.next()
...     while 1:
...         if ng < nh:
...             yield ng
...             ng = g.next()
...         elif ng > nh:
...             yield nh
...             nh = h.next()
...         else:
...             yield ng
...             ng = g.next()
...             nh = h.next()
 
The following works, but is doing a whale of a lot of redundant work --
it's not clear how to get the internal uses of m235 to share a single
generator.  Note that me_times2 (etc) each need to see every element in the
result sequence.  So this is an example where lazy lists are more natural
(you can look at the head of a lazy list any number of times).
 
>>> def m235():
...     yield 1
...     me_times2 = times(2, m235())
...     me_times3 = times(3, m235())
...     me_times5 = times(5, m235())
...     for i in merge(merge(me_times2,
...                          me_times3),
...                    me_times5):
...         yield i
 
Don't print "too many" of these -- the implementation above is extremely
inefficient:  each call of m235() leads to 3 recursive calls, and in
turn each of those 3 more, and so on, and so on, until we've descended
enough levels to satisfy the print stmts.  Very odd:  when I printed 5
lines of results below, this managed to screw up Win98's malloc in "the
usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting
address space, and it *looked* like a very slow leak.
 
>>> result = m235()
>>> for i in range(3):
...     print firstn(result, 15)
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
 
Heh.  Here's one way to get a shared list, complete with an excruciating
namespace renaming trick.  The *pretty* part is that the times() and merge()
functions can be reused as-is, because they only assume their stream
arguments are iterable -- a LazyList is the same as a generator to times().
 
>>> class LazyList:
...     def __init__(self, g):
...         self.sofar = []
...         self.fetch = g.next
...
...     def __getitem__(self, i):
...         sofar, fetch = self.sofar, self.fetch
...         while i >= len(sofar):
...             sofar.append(fetch())
...         return sofar[i]
 
>>> def m235():
...     yield 1
...     # Gack:  m235 below actually refers to a LazyList.
...     me_times2 = times(2, m235)
...     me_times3 = times(3, m235)
...     me_times5 = times(5, m235)
...     for i in merge(merge(me_times2,
...                          me_times3),
...                    me_times5):
...         yield i
 
Print as many of these as you like -- *this* implementation is memory-
efficient.
 
>>> m235 = LazyList(m235())
>>> for i in range(5):
...     print [m235[j] for j in range(15*i, 15*(i+1))]
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
[200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
[400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
 
Ye olde Fibonacci generator, LazyList style.
 
>>> def fibgen(a, b):
...
...     def sum(g, h):
...         while 1:
...             yield g.next() + h.next()
...
...     def tail(g):
...         g.next()    # throw first away
...         for x in g:
...             yield x
...
...     yield a
...     yield b
...     for s in sum(iter(fib),
...                  tail(iter(fib))):
...         yield s
 
>>> fib = LazyList(fibgen(1, 2))
>>> firstn(iter(fib), 17)
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
 
 
Running after your tail with itertools.tee (new in version 2.4)
 
The algorithms "m235" (Hamming) and Fibonacci presented above are both
examples of a whole family of FP (functional programming) algorithms
where a function produces and returns a list while the production algorithm
suppose the list as already produced by recursively calling itself.
For these algorithms to work, they must:
 
- produce at least a first element without presupposing the existence of
  the rest of the list
- produce their elements in a lazy manner
 
To work efficiently, the beginning of the list must not be recomputed over
and over again. This is ensured in most FP languages as a built-in feature.
In python, we have to explicitly maintain a list of already computed results
and abandon genuine recursivity.
 
This is what had been attempted above with the LazyList class. One problem
with that class is that it keeps a list of all of the generated results and
therefore continually grows. This partially defeats the goal of the generator
concept, viz. produce the results only as needed instead of producing them
all and thereby wasting memory.
 
Thanks to itertools.tee, it is now clear "how to get the internal uses of
m235 to share a single generator".
 
>>> from itertools import tee
>>> def m235():
...     def _m235():
...         yield 1
...         for n in merge(times(2, m2),
...                        merge(times(3, m3),
...                              times(5, m5))):
...             yield n
...     m1 = _m235()
...     m2, m3, m5, mRes = tee(m1, 4)
...     return mRes
 
>>> it = m235()
>>> for i in range(5):
...     print firstn(it, 15)
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
[200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
[400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
 
The "tee" function does just what we want. It internally keeps a generated
result for as long as it has not been "consumed" from all of the duplicated
iterators, whereupon it is deleted. You can therefore print the hamming
sequence during hours without increasing memory usage, or very little.
 
The beauty of it is that recursive running-after-their-tail FP algorithms
are quite straightforwardly expressed with this Python idiom.
 
Ye olde Fibonacci generator, tee style.
 
>>> def fib():
...
...     def _isum(g, h):
...         while 1:
...             yield g.next() + h.next()
...
...     def _fib():
...         yield 1
...         yield 2
...         fibTail.next() # throw first away
...         for res in _isum(fibHead, fibTail):
...             yield res
...
...     realfib = _fib()
...     fibHead, fibTail, fibRes = tee(realfib, 3)
...     return fibRes
 
>>> firstn(fib(), 17)
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
 
s›
 
>>> def f():
...     return 22
...     yield 1
Traceback (most recent call last):
  ..
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[0]>, line 3)
 
>>> def f():
...     yield 1
...     return 22
Traceback (most recent call last):
  ..
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[1]>, line 3)
 
"return None" is not the same as "return" in a generator:
 
>>> def f():
...     yield 1
...     return None
Traceback (most recent call last):
  ..
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[2]>, line 3)
 
These are fine:
 
>>> def f():
...     yield 1
...     return
 
>>> def f():
...     try:
...         yield 1
...     finally:
...         pass
 
>>> def f():
...     try:
...         try:
...             1//0
...         except ZeroDivisionError:
...             yield 666
...         except:
...             pass
...     finally:
...         pass
 
>>> def f():
...     try:
...         try:
...             yield 12
...             1//0
...         except ZeroDivisionError:
...             yield 666
...         except:
...             try:
...                 x = 12
...             finally:
...                 yield 12
...     except:
...         return
>>> list(f())
[12, 666]
 
>>> def f():
...    yield
>>> type(f())
<type 'generator'>
 
 
>>> def f():
...    if 0:
...        yield
>>> type(f())
<type 'generator'>
 
 
>>> def f():
...     if 0:
...         yield 1
>>> type(f())
<type 'generator'>
 
>>> def f():
...    if "":
...        yield None
>>> type(f())
<type 'generator'>
 
>>> def f():
...     return
...     try:
...         if x==4:
...             pass
...         elif 0:
...             try:
...                 1//0
...             except SyntaxError:
...                 pass
...             else:
...                 if 0:
...                     while 12:
...                         x += 1
...                         yield 2 # don't blink
...                         f(a, b, c, d, e)
...         else:
...             pass
...     except:
...         x = 1
...     return
>>> type(f())
<type 'generator'>
 
>>> def f():
...     if 0:
...         def g():
...             yield 1
...
>>> type(f())
<type 'NoneType'>
 
>>> def f():
...     if 0:
...         class C:
...             def __init__(self):
...                 yield 1
...             def f(self):
...                 yield 2
>>> type(f())
<type 'NoneType'>
 
>>> def f():
...     if 0:
...         return
...     if 0:
...         yield 2
>>> type(f())
<type 'generator'>
 
 
>>> def f():
...     if 0:
...         lambda x:  x        # shouldn't trigger here
...         return              # or here
...         def f(i):
...             return 2*i      # or here
...         if 0:
...             return 3        # but *this* sucks (line 8)
...     if 0:
...         yield 2             # because it's a generator (line 10)
Traceback (most recent call last):
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[24]>, line 10)
 
This one caused a crash (see SF bug 567538):
 
>>> def f():
...     for i in range(3):
...         try:
...             continue
...         finally:
...             yield i
...
>>> g = f()
>>> print g.next()
0
>>> print g.next()
1
>>> print g.next()
2
>>> print g.next()
Traceback (most recent call last):
StopIteration
 
 
Test the gi_code attribute
 
>>> def f():
...     yield 5
...
>>> g = f()
>>> g.gi_code is f.func_code
True
>>> g.next()
5
>>> g.next()
Traceback (most recent call last):
StopIteration
>>> g.gi_code is f.func_code
True
 
 
Test the __name__ attribute and the repr()
 
>>> def f():
...    yield 5
...
>>> g = f()
>>> g.__name__
'f'
>>> repr(g)  # doctest: +ELLIPSIS
'<generator object f at ...>'
 
Lambdas shouldn't have their usual return behavior.
 
>>> x = lambda: (yield 1)
>>> list(x())
[1]
 
>>> x = lambda: ((yield 1), (yield 2))
>>> list(x())
[1, 2]
c#sHdgtˆƒ‰‡‡‡fd†‰xˆdƒD] }|Vq5WdS(Nc3sZ|tˆƒkrˆVn<x9ˆ|ƒD]*ˆ|<xˆ|dƒD] }|VqCWq(WdS(Ni(tlen(titx(tgentgstvalues(s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyRÈs
i(tNoneR(RR((RRRs\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pytsimple_conjoinÄsc#sltˆƒ‰dgˆ‰‡‡‡‡‡fd†‰‡‡‡‡fd†‰xˆdƒD] }|VqYWdS(Nc3s‡|ˆkrˆVnoˆ|drg|d}xTˆ|ƒD]&ˆ|<xˆ|ƒD] }|VqQWq:Wnxˆ|ƒD] }|VqtWdS(Nii((Rtip1R(t_gen3RRtnR(s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyRás 
c3sú|d|d|d}}}ˆ||!\}}}|ˆkr’x±|ƒD]?ˆ|<x2|ƒD]'ˆ|<x|ƒD]ˆ|<ˆVqtWq`WqLWndxa|ƒD]Vˆ|<xI|ƒD]>ˆ|<x1|ƒD]&ˆ|<xˆ|ƒD] }|VqÛWqÄWq°WqœWdS(Niii((RRtip2tip3tgtg1tg2R(R    RR
R(s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyR    ós  i(RR(RR((R    RRR
Rs\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pytconjoinÙs   ccs÷t|ƒ}dg|}dg|}t}d}x¾yFx?||kry||ƒj}||<|ƒ||<|d7}q;WWn|k
rŽnX|V|d8}xO|dkrîy ||ƒ||<|d7}PWq¡|k
rê|d8}q¡Xq¡WPq5dS(Nii(RRt StopIterationtnext(RR
Rtiterst_StopIterationRtit((s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyt flat_conjoins.     
 
 tQueenscBs#eZd„Zd„Zd„ZRS(cs©|ˆ_t|ƒ‰gˆ_x„ˆD]|}gˆD]D}d|>d||||d>Bd|d|d||>B^q2}|‡‡fd†}ˆjj|ƒq%WdS(Nliic3sYxRˆD]J}||}|ˆj@dkrˆj|O_|Vˆj|M_qqWdS(Ni(tused(trowusestjtuses(trangentself(s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pytrowgenQs  
(R
tranget rowgeneratorstappend(RR
RRRR((RRs\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyt__init__;s         Nccs,d|_xt|jƒD] }|VqWdS(Ni(RRR (Rtrow2col((s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pytsolve\s    cCs|j}dd|}|GHx\t|ƒD]N}gt|ƒD] }d^q<}d|||<ddj|ƒdGH|GHq)WdS(Nt+s-+t tQt|(R
Rtjoin(RR#R
tsepRRtsquares((s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyt printsolutionas    (t__name__t
__module__R"R$R,(((s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyR:s    !    tKnightscBsAeZdd„Zd„Zd„Zd„Zd„Zd„ZRS(ic    s0ˆˆˆ_ˆ_g‰ˆ_t‡fd†‰‡fd†‰‡‡‡‡‡fd†}‡‡‡‡‡‡fd†}t‡‡‡‡fd†}ˆddˆddt‡‡‡‡fd†}‡‡fd    †}ˆˆd
kr÷|gˆ_n5||g|r |p|gˆˆd |gˆ_dS( NcsŠd}}xgˆ|D][}ˆ|}|j|ƒ||ƒ}|dkrW|d7}q|dkr|d7}qqW|dko‰|dkS(Niii(tremove(ti0Rtne0tne1Rtste(tsuccs(s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pytremove_from_successors}s    
 
     cs*x#ˆ|D]}ˆ|j|ƒq WdS(N(R!(R1R(R6(s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pytadd_to_successors“sc3sTˆdksˆdkrdSˆjddƒ}ˆ|ƒ|ˆ_|Vˆ|ƒdS(Nii(t coords2indextlastij(tcorner(R8tmR
R7R(s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pytfirst˜s
    c3sȈjddƒ}ˆdks*ˆdkr.dSx“ddfD]…\}}ˆj||ƒ}ˆjd|d|ƒ}|ˆ_ˆ|ƒˆ|j|ƒ|ˆ_|Vˆ|j|ƒˆ|ƒq;WdS(Niiii(ii(ii(R9tfinalR!R:R0(R;RRtthisR>(R8R<R
R7RR6(s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pytsecond¥s    
    c3s¾g}xaˆˆjD]H}|ˆ|ƒ}|dkrI||fg}Pn|j||fƒqW|jƒxM|D]E\}}|ˆjkrqˆ|ƒr©|ˆ_|Vnˆ|ƒqqqqWdS(Ni(R:R!tsortR>(Rt
candidatesRR5(R8R7RR6(s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pytadvance¾s 
     ig@c    3s÷g}x—ˆˆjD]~}|ˆ|ƒ}|dkrL|d|fg}Pnˆj|ƒ\}}||d||d}|j|| |fƒqW|jƒxP|D]H\}}}|ˆjkr§ˆ|ƒrâ|ˆ_|Vnˆ|ƒq§q§WdS(Niii(R:t index2coordsR!RAR>(    tvmidthmidRRBRR5ti1tj1td(R8R7RR6(s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyt advance_hardØs  
     c3s ˆjVdS(N(R>((RR6(s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pytlastòsii(R<R
R6Rtsquaregenerators(    RR<R
thardR=R@RCRJRK((R8R<R
R7RR6s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyR"rs  1(cCs||j|S(N(R
(RRR((s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyR9ýscCst||jƒS(N(tdivmodR
(Rtindex((s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyRDsc Csü|j}|2|j|j}}|j}dddd    d
d d d g}t|ƒ}x¢t|ƒD]”}x‹|D]ƒ}g|D]c\}    }
d||    ko¡|knrzd||
koÁ|knrz|||    ||
ƒ^qz} |j| ƒqmWq`WdS(Niiiÿÿÿÿiþÿÿÿi(ii(ii(iiÿÿÿÿ(iiþÿÿÿ(iÿÿÿÿiþÿÿÿ(iþÿÿÿiÿÿÿÿ(iþÿÿÿi(iÿÿÿÿi(R6R<R
R9RR!( RR6R<R
tc2itoffsetsRRRtiotjoR4((s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyt _init_boards            =ccs-|jƒxt|jƒD] }|VqWdS(N(RTRRL(RR((s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyR$s
c Cs|j|j}}tt||ƒƒ}dt|ƒd}gt|ƒD]}dg|^qJ}d}x?|D]7}|j|ƒ\}    }
||||    |
<|d7}qpWdd|d|} | GHx9t|ƒD]+}||} ddj| ƒdGH| GHqÓWdS(Nt%RIiR%t-R((R<R
RtstrRRRDR)( RRR<R
twtformatRR+tkRGRHR*trow((s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyR,s& 
(R-R.R"R9RDRTR$R,(((s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyR/qs  ‹                s`
 
Generate the 3-bit binary numbers in order.  This illustrates dumbest-
possible use of conjoin, just to generate the full cross-product.
 
>>> for c in conjoin([lambda: iter((0, 1))] * 3):
...     print c
[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[1, 1, 1]
 
For efficiency in typical backtracking apps, conjoin() yields the same list
object each time.  So if you want to save away a full account of its
generated sequence, you need to copy its results.
 
>>> def gencopy(iterator):
...     for x in iterator:
...         yield x[:]
 
>>> for n in range(10):
...     all = list(gencopy(conjoin([lambda: iter((0, 1))] * n)))
...     print n, len(all), all[0] == [0] * n, all[-1] == [1] * n
0 1 True True
1 2 True True
2 4 True True
3 8 True True
4 16 True True
5 32 True True
6 64 True True
7 128 True True
8 256 True True
9 512 True True
 
And run an 8-queens solver.
 
>>> q = Queens(8)
>>> LIMIT = 2
>>> count = 0
>>> for row2col in q.solve():
...     count += 1
...     if count <= LIMIT:
...         print "Solution", count
...         q.printsolution(row2col)
Solution 1
+-+-+-+-+-+-+-+-+
|Q| | | | | | | |
+-+-+-+-+-+-+-+-+
| | | | |Q| | | |
+-+-+-+-+-+-+-+-+
| | | | | | | |Q|
+-+-+-+-+-+-+-+-+
| | | | | |Q| | |
+-+-+-+-+-+-+-+-+
| | |Q| | | | | |
+-+-+-+-+-+-+-+-+
| | | | | | |Q| |
+-+-+-+-+-+-+-+-+
| |Q| | | | | | |
+-+-+-+-+-+-+-+-+
| | | |Q| | | | |
+-+-+-+-+-+-+-+-+
Solution 2
+-+-+-+-+-+-+-+-+
|Q| | | | | | | |
+-+-+-+-+-+-+-+-+
| | | | | |Q| | |
+-+-+-+-+-+-+-+-+
| | | | | | | |Q|
+-+-+-+-+-+-+-+-+
| | |Q| | | | | |
+-+-+-+-+-+-+-+-+
| | | | | | |Q| |
+-+-+-+-+-+-+-+-+
| | | |Q| | | | |
+-+-+-+-+-+-+-+-+
| |Q| | | | | | |
+-+-+-+-+-+-+-+-+
| | | | |Q| | | |
+-+-+-+-+-+-+-+-+
 
>>> print count, "solutions in all."
92 solutions in all.
 
And run a Knight's Tour on a 10x10 board.  Note that there are about
20,000 solutions even on a 6x6 board, so don't dare run this to exhaustion.
 
>>> k = Knights(10, 10)
>>> LIMIT = 2
>>> count = 0
>>> for x in k.solve():
...     count += 1
...     if count <= LIMIT:
...         print "Solution", count
...         k.printsolution(x)
...     else:
...         break
Solution 1
+---+---+---+---+---+---+---+---+---+---+
|  1| 58| 27| 34|  3| 40| 29| 10|  5|  8|
+---+---+---+---+---+---+---+---+---+---+
| 26| 35|  2| 57| 28| 33|  4|  7| 30| 11|
+---+---+---+---+---+---+---+---+---+---+
| 59|100| 73| 36| 41| 56| 39| 32|  9|  6|
+---+---+---+---+---+---+---+---+---+---+
| 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
+---+---+---+---+---+---+---+---+---+---+
| 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
+---+---+---+---+---+---+---+---+---+---+
| 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
+---+---+---+---+---+---+---+---+---+---+
| 87| 98| 91| 80| 77| 84| 53| 46| 65| 44|
+---+---+---+---+---+---+---+---+---+---+
| 90| 23| 88| 95| 70| 79| 68| 83| 14| 17|
+---+---+---+---+---+---+---+---+---+---+
| 97| 92| 21| 78| 81| 94| 19| 16| 45| 66|
+---+---+---+---+---+---+---+---+---+---+
| 22| 89| 96| 93| 20| 69| 82| 67| 18| 15|
+---+---+---+---+---+---+---+---+---+---+
Solution 2
+---+---+---+---+---+---+---+---+---+---+
|  1| 58| 27| 34|  3| 40| 29| 10|  5|  8|
+---+---+---+---+---+---+---+---+---+---+
| 26| 35|  2| 57| 28| 33|  4|  7| 30| 11|
+---+---+---+---+---+---+---+---+---+---+
| 59|100| 73| 36| 41| 56| 39| 32|  9|  6|
+---+---+---+---+---+---+---+---+---+---+
| 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
+---+---+---+---+---+---+---+---+---+---+
| 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
+---+---+---+---+---+---+---+---+---+---+
| 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
+---+---+---+---+---+---+---+---+---+---+
| 87| 98| 89| 80| 77| 84| 53| 46| 65| 44|
+---+---+---+---+---+---+---+---+---+---+
| 90| 23| 92| 95| 70| 79| 68| 83| 14| 17|
+---+---+---+---+---+---+---+---+---+---+
| 97| 88| 21| 78| 81| 94| 19| 16| 45| 66|
+---+---+---+---+---+---+---+---+---+---+
| 22| 91| 96| 93| 20| 69| 82| 67| 18| 15|
+---+---+---+---+---+---+---+---+---+---+
sMGenerators are weakly referencable:
 
>>> import weakref
>>> def gen():
...     yield 'foo!'
...
>>> wr = weakref.ref(gen)
>>> wr() is gen
True
>>> p = weakref.proxy(gen)
 
Generator-iterators are weakly referencable as well:
 
>>> gi = gen()
>>> wr = weakref.ref(gi)
>>> wr() is gi
True
>>> p = weakref.proxy(gi)
>>> list(p)
['foo!']
 
sVSending a value into a started generator:
 
>>> def f():
...     print (yield 1)
...     yield 2
>>> g = f()
>>> g.next()
1
>>> g.send(42)
42
2
 
Sending a value into a new generator produces a TypeError:
 
>>> f().send("foo")
Traceback (most recent call last):
...
TypeError: can't send non-None value to a just-started generator
 
 
Yield by itself yields None:
 
>>> def f(): yield
>>> list(f())
[None]
 
 
 
An obscene abuse of a yield expression within a generator expression:
 
>>> list((yield 21) for i in range(4))
[21, None, 21, None, 21, None, 21, None]
 
And a more sane, but still weird usage:
 
>>> def f(): list(i for i in [(yield 26)])
>>> type(f())
<type 'generator'>
 
 
A yield expression with augmented assignment.
 
>>> def coroutine(seq):
...     count = 0
...     while count < 200:
...         count += yield
...         seq.append(count)
>>> seq = []
>>> c = coroutine(seq)
>>> c.next()
>>> print seq
[]
>>> c.send(10)
>>> print seq
[10]
>>> c.send(10)
>>> print seq
[10, 20]
>>> c.send(10)
>>> print seq
[10, 20, 30]
 
 
Check some syntax errors for yield expressions:
 
>>> f=lambda: (yield 1),(yield 2)
Traceback (most recent call last):
  ...
  File "<doctest test.test_generators.__test__.coroutine[21]>", line 1
SyntaxError: 'yield' outside function
 
>>> def f(): return lambda x=(yield): 1
Traceback (most recent call last):
  ...
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.coroutine[22]>, line 1)
 
>>> def f(): x = yield = y
Traceback (most recent call last):
  ...
  File "<doctest test.test_generators.__test__.coroutine[23]>", line 1
SyntaxError: assignment to yield expression not possible
 
>>> def f(): (yield bar) = y
Traceback (most recent call last):
  ...
  File "<doctest test.test_generators.__test__.coroutine[24]>", line 1
SyntaxError: can't assign to yield expression
 
>>> def f(): (yield bar) += y
Traceback (most recent call last):
  ...
  File "<doctest test.test_generators.__test__.coroutine[25]>", line 1
SyntaxError: can't assign to yield expression
 
 
Now check some throw() conditions:
 
>>> def f():
...     while True:
...         try:
...             print (yield)
...         except ValueError,v:
...             print "caught ValueError (%s)" % (v),
>>> import sys
>>> g = f()
>>> g.next()
 
>>> g.throw(ValueError) # type only
caught ValueError ()
 
>>> g.throw(ValueError("xyz"))  # value only
caught ValueError (xyz)
 
>>> g.throw(ValueError, ValueError(1))   # value+matching type
caught ValueError (1)
 
>>> g.throw(ValueError, TypeError(1))  # mismatched type, rewrapped
caught ValueError (1)
 
>>> g.throw(ValueError, ValueError(1), None)   # explicit None traceback
caught ValueError (1)
 
>>> g.throw(ValueError(1), "foo")       # bad args
Traceback (most recent call last):
  ...
TypeError: instance exception may not have a separate value
 
>>> g.throw(ValueError, "foo", 23)      # bad args
Traceback (most recent call last):
  ...
TypeError: throw() third argument must be a traceback object
 
>>> def throw(g,exc):
...     try:
...         raise exc
...     except:
...         g.throw(*sys.exc_info())
>>> throw(g,ValueError) # do it with traceback included
caught ValueError ()
 
>>> g.send(1)
1
 
>>> throw(g,TypeError)  # terminate the generator
Traceback (most recent call last):
  ...
TypeError
 
>>> print g.gi_frame
None
 
>>> g.send(2)
Traceback (most recent call last):
  ...
StopIteration
 
>>> g.throw(ValueError,6)       # throw on closed generator
Traceback (most recent call last):
  ...
ValueError: 6
 
>>> f().throw(ValueError,7)     # throw on just-opened generator
Traceback (most recent call last):
  ...
ValueError: 7
 
>>> f().throw("abc")     # throw on just-opened generator
Traceback (most recent call last):
  ...
TypeError: exceptions must be classes, or instances, not str
 
Now let's try closing a generator:
 
>>> def f():
...     try: yield
...     except GeneratorExit:
...         print "exiting"
 
>>> g = f()
>>> g.next()
>>> g.close()
exiting
>>> g.close()  # should be no-op now
 
>>> f().close()  # close on just-opened generator should be fine
 
>>> def f(): yield      # an even simpler generator
>>> f().close()         # close before opening
>>> g = f()
>>> g.next()
>>> g.close()           # close normally
 
And finalization:
 
>>> def f():
...     try: yield
...     finally:
...         print "exiting"
 
>>> g = f()
>>> g.next()
>>> del g
exiting
 
>>> class context(object):
...    def __enter__(self): pass
...    def __exit__(self, *args): print 'exiting'
>>> def f():
...     with context():
...          yield
>>> g = f()
>>> g.next()
>>> del g
exiting
 
 
GeneratorExit is not caught by except Exception:
 
>>> def f():
...     try: yield
...     except Exception: print 'except'
...     finally: print 'finally'
 
>>> g = f()
>>> g.next()
>>> del g
finally
 
 
Now let's try some ill-behaved generators:
 
>>> def f():
...     try: yield
...     except GeneratorExit:
...         yield "foo!"
>>> g = f()
>>> g.next()
>>> g.close()
Traceback (most recent call last):
  ...
RuntimeError: generator ignored GeneratorExit
>>> g.close()
 
 
Our ill-behaved code should be invoked during GC:
 
>>> import sys, StringIO
>>> old, sys.stderr = sys.stderr, StringIO.StringIO()
>>> g = f()
>>> g.next()
>>> del g
>>> sys.stderr.getvalue().startswith(
...     "Exception RuntimeError: 'generator ignored GeneratorExit' in "
... )
True
>>> sys.stderr = old
 
 
And errors thrown during closing should propagate:
 
>>> def f():
...     try: yield
...     except GeneratorExit:
...         raise TypeError("fie!")
>>> g = f()
>>> g.next()
>>> g.close()
Traceback (most recent call last):
  ...
TypeError: fie!
 
 
Ensure that various yield expression constructs make their
enclosing function a generator:
 
>>> def f(): x += yield
>>> type(f())
<type 'generator'>
 
>>> def f(): x = yield
>>> type(f())
<type 'generator'>
 
>>> def f(): lambda x=(yield): 1
>>> type(f())
<type 'generator'>
 
>>> def f(): x=(i for i in (yield) if (yield))
>>> type(f())
<type 'generator'>
 
>>> def f(d): d[(yield "a")] = d[(yield "b")] = 27
>>> data = [1,2]
>>> g = f(data)
>>> type(g)
<type 'generator'>
>>> g.send(None)
'a'
>>> data
[1, 2]
>>> g.send(0)
'b'
>>> data
[27, 2]
>>> try: g.send(1)
... except StopIteration: pass
>>> data
[27, 27]
 
sS
Prior to adding cycle-GC support to itertools.tee, this code would leak
references. We add it to the standard suite so the routine refleak-tests
would trigger if it starts being uncleanable again.
 
>>> import itertools
>>> def leak():
...     class gen:
...         def __iter__(self):
...             return self
...         def next(self):
...             return self.item
...     g = gen()
...     head, tail = itertools.tee(g)
...     g.item = head
...     return head
>>> it = leak()
 
Make sure to also test the involvement of the tee-internal teedataobject,
which stores returned items.
 
>>> item = it.next()
 
 
 
This test leaked at one point due to generator finalization/destruction.
It was copied from Lib/test/leakers/test_generator_cycle.py before the file
was removed.
 
>>> def leak():
...    def gen():
...        while True:
...            yield g
...    g = gen()
 
>>> leak()
 
 
 
This test isn't really generator related, but rather exception-in-cleanup
related. The coroutine tests (above) just happen to cause an exception in
the generator's __del__ (tp_del) method. We can also test for this
explicitly, without generators. We do have to redirect stderr to avoid
printing warnings and to doublecheck that we actually tested what we wanted
to test.
 
>>> import sys, StringIO
>>> old = sys.stderr
>>> try:
...     sys.stderr = StringIO.StringIO()
...     class Leaker:
...         def __del__(self):
...             raise RuntimeError
...
...     l = Leaker()
...     del l
...     err = sys.stderr.getvalue().strip()
...     err.startswith(
...         "Exception RuntimeError: RuntimeError() in <"
...     )
...     err.endswith("> ignored")
...     len(err.splitlines())
... finally:
...     sys.stderr = old
True
True
1
 
 
 
These refleak tests should perhaps be in a testfile of their own,
test_generators just happened to be the test that drew these out.
 
ttuttpeptemailtfuntsyntaxRtweakreft    coroutinetrefleakscCs*ddlm}m}|j||ƒdS(Niÿÿÿÿ(t test_supportttest_generators(ttestRdRet run_doctest(tverboseRdRe((s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyt    test_mainmst__main__iN(ttutorial_testst    pep_testst email_testst    fun_testst syntax_testsRRRRR/t conjoin_testst weakref_teststcoroutine_teststrefleaks_testst__test__RRiR-(((s\/tmp/ndk-User/buildhost/install/prebuilt/darwin-x86_64/lib/python2.7/test/test_generators.pyt<module>„s6¥¾îÙ        =    $7ÿQÿ9K