blob: a77e9587f3af2dc244a144929247d81e256218cb [file] [log] [blame]
Tim Peters6ba5f792001-06-23 20:45:43 +00001tutorial_tests = """
Tim Peters1def3512001-06-23 20:27:04 +00002Let's try a simple generator:
3
4 >>> def f():
5 ... yield 1
6 ... yield 2
7
Tim Petersb9e9ff12001-06-24 03:44:52 +00008 >>> for i in f():
9 ... print i
10 1
11 2
Tim Peters1def3512001-06-23 20:27:04 +000012 >>> g = f()
13 >>> g.next()
14 1
15 >>> g.next()
16 2
Tim Petersea2e97a2001-06-24 07:10:02 +000017
Tim Peters2106ef02001-06-25 01:30:12 +000018"Falling off the end" stops the generator:
Tim Petersea2e97a2001-06-24 07:10:02 +000019
Tim Peters1def3512001-06-23 20:27:04 +000020 >>> g.next()
21 Traceback (most recent call last):
22 File "<stdin>", line 1, in ?
23 File "<stdin>", line 2, in g
24 StopIteration
25
Tim Petersea2e97a2001-06-24 07:10:02 +000026"return" also stops the generator:
Tim Peters1def3512001-06-23 20:27:04 +000027
28 >>> def f():
29 ... yield 1
30 ... return
31 ... yield 2 # never reached
32 ...
33 >>> g = f()
34 >>> g.next()
35 1
36 >>> g.next()
37 Traceback (most recent call last):
38 File "<stdin>", line 1, in ?
39 File "<stdin>", line 3, in f
40 StopIteration
41 >>> g.next() # once stopped, can't be resumed
42 Traceback (most recent call last):
43 File "<stdin>", line 1, in ?
44 StopIteration
45
46"raise StopIteration" stops the generator too:
47
48 >>> def f():
49 ... yield 1
Tim Peters34463652001-07-12 22:43:41 +000050 ... raise StopIteration
Tim Peters1def3512001-06-23 20:27:04 +000051 ... yield 2 # never reached
52 ...
53 >>> g = f()
54 >>> g.next()
55 1
56 >>> g.next()
57 Traceback (most recent call last):
58 File "<stdin>", line 1, in ?
59 StopIteration
60 >>> g.next()
61 Traceback (most recent call last):
62 File "<stdin>", line 1, in ?
63 StopIteration
64
65However, they are not exactly equivalent:
66
67 >>> def g1():
68 ... try:
69 ... return
70 ... except:
71 ... yield 1
72 ...
73 >>> list(g1())
74 []
75
76 >>> def g2():
77 ... try:
78 ... raise StopIteration
79 ... except:
80 ... yield 42
81 >>> print list(g2())
82 [42]
83
84This may be surprising at first:
85
86 >>> def g3():
87 ... try:
88 ... return
89 ... finally:
90 ... yield 1
91 ...
92 >>> list(g3())
93 [1]
94
95Let's create an alternate range() function implemented as a generator:
96
97 >>> def yrange(n):
98 ... for i in range(n):
99 ... yield i
100 ...
101 >>> list(yrange(5))
102 [0, 1, 2, 3, 4]
103
104Generators always return to the most recent caller:
105
106 >>> def creator():
107 ... r = yrange(5)
108 ... print "creator", r.next()
109 ... return r
110 ...
111 >>> def caller():
112 ... r = creator()
113 ... for i in r:
114 ... print "caller", i
115 ...
116 >>> caller()
117 creator 0
118 caller 1
119 caller 2
120 caller 3
121 caller 4
122
123Generators can call other generators:
124
125 >>> def zrange(n):
126 ... for i in yrange(n):
127 ... yield i
128 ...
129 >>> list(zrange(5))
130 [0, 1, 2, 3, 4]
131
132"""
133
Tim Peters6ba5f792001-06-23 20:45:43 +0000134# The examples from PEP 255.
135
136pep_tests = """
137
Tim Peterse5614632001-08-15 04:41:19 +0000138Specification: Yield
139
140 Restriction: A generator cannot be resumed while it is actively
141 running:
142
143 >>> def g():
144 ... i = me.next()
145 ... yield i
146 >>> me = g()
147 >>> me.next()
148 Traceback (most recent call last):
149 ...
150 File "<string>", line 2, in g
151 ValueError: generator already executing
152
Tim Peters6ba5f792001-06-23 20:45:43 +0000153Specification: Return
154
155 Note that return isn't always equivalent to raising StopIteration: the
156 difference lies in how enclosing try/except constructs are treated.
157 For example,
158
159 >>> def f1():
160 ... try:
161 ... return
162 ... except:
163 ... yield 1
164 >>> print list(f1())
165 []
166
167 because, as in any function, return simply exits, but
168
169 >>> def f2():
170 ... try:
171 ... raise StopIteration
172 ... except:
173 ... yield 42
174 >>> print list(f2())
175 [42]
176
177 because StopIteration is captured by a bare "except", as is any
178 exception.
179
180Specification: Generators and Exception Propagation
181
182 >>> def f():
Tim Peters3caca232001-12-06 06:23:26 +0000183 ... return 1//0
Tim Peters6ba5f792001-06-23 20:45:43 +0000184 >>> def g():
185 ... yield f() # the zero division exception propagates
186 ... yield 42 # and we'll never get here
187 >>> k = g()
188 >>> k.next()
189 Traceback (most recent call last):
190 File "<stdin>", line 1, in ?
191 File "<stdin>", line 2, in g
192 File "<stdin>", line 2, in f
193 ZeroDivisionError: integer division or modulo by zero
194 >>> k.next() # and the generator cannot be resumed
195 Traceback (most recent call last):
196 File "<stdin>", line 1, in ?
197 StopIteration
198 >>>
199
200Specification: Try/Except/Finally
201
202 >>> def f():
203 ... try:
204 ... yield 1
205 ... try:
206 ... yield 2
Tim Peters3caca232001-12-06 06:23:26 +0000207 ... 1//0
Tim Peters6ba5f792001-06-23 20:45:43 +0000208 ... yield 3 # never get here
209 ... except ZeroDivisionError:
210 ... yield 4
211 ... yield 5
212 ... raise
213 ... except:
214 ... yield 6
215 ... yield 7 # the "raise" above stops this
216 ... except:
217 ... yield 8
218 ... yield 9
219 ... try:
220 ... x = 12
221 ... finally:
222 ... yield 10
223 ... yield 11
224 >>> print list(f())
225 [1, 2, 4, 5, 8, 9, 10, 11]
226 >>>
227
Tim Peters6ba5f792001-06-23 20:45:43 +0000228Guido's binary tree example.
229
230 >>> # A binary tree class.
231 >>> class Tree:
232 ...
233 ... def __init__(self, label, left=None, right=None):
234 ... self.label = label
235 ... self.left = left
236 ... self.right = right
237 ...
238 ... def __repr__(self, level=0, indent=" "):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000239 ... s = level*indent + repr(self.label)
Tim Peters6ba5f792001-06-23 20:45:43 +0000240 ... if self.left:
241 ... s = s + "\\n" + self.left.__repr__(level+1, indent)
242 ... if self.right:
243 ... s = s + "\\n" + self.right.__repr__(level+1, indent)
244 ... return s
245 ...
246 ... def __iter__(self):
247 ... return inorder(self)
248
249 >>> # Create a Tree from a list.
250 >>> def tree(list):
251 ... n = len(list)
252 ... if n == 0:
253 ... return []
Tim Peters3caca232001-12-06 06:23:26 +0000254 ... i = n // 2
Tim Peters6ba5f792001-06-23 20:45:43 +0000255 ... return Tree(list[i], tree(list[:i]), tree(list[i+1:]))
256
257 >>> # Show it off: create a tree.
258 >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
259
Tim Petersd674e172002-03-10 07:59:13 +0000260 >>> # A recursive generator that generates Tree labels in in-order.
Tim Peters6ba5f792001-06-23 20:45:43 +0000261 >>> def inorder(t):
262 ... if t:
263 ... for x in inorder(t.left):
264 ... yield x
265 ... yield t.label
266 ... for x in inorder(t.right):
267 ... yield x
268
269 >>> # Show it off: create a tree.
Edward Loper103d26e2004-08-09 02:03:30 +0000270 >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
271 >>> # Print the nodes of the tree in in-order.
272 >>> for x in t:
Tim Peters6ba5f792001-06-23 20:45:43 +0000273 ... print x,
274 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
275
276 >>> # A non-recursive generator.
277 >>> def inorder(node):
278 ... stack = []
279 ... while node:
280 ... while node.left:
281 ... stack.append(node)
282 ... node = node.left
283 ... yield node.label
284 ... while not node.right:
285 ... try:
286 ... node = stack.pop()
287 ... except IndexError:
288 ... return
289 ... yield node.label
290 ... node = node.right
291
292 >>> # Exercise the non-recursive generator.
293 >>> for x in t:
294 ... print x,
295 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
296
297"""
298
Tim Petersb2bc6a92001-06-24 10:14:27 +0000299# Examples from Iterator-List and Python-Dev and c.l.py.
Tim Peters6ba5f792001-06-23 20:45:43 +0000300
301email_tests = """
302
303The difference between yielding None and returning it.
304
305>>> def g():
306... for i in range(3):
307... yield None
308... yield None
309... return
310>>> list(g())
311[None, None, None, None]
312
313Ensure that explicitly raising StopIteration acts like any other exception
314in try/except, not like a return.
315
316>>> def g():
317... yield 1
318... try:
319... raise StopIteration
320... except:
321... yield 2
322... yield 3
323>>> list(g())
324[1, 2, 3]
Tim Petersb9e9ff12001-06-24 03:44:52 +0000325
Tim Petersb2bc6a92001-06-24 10:14:27 +0000326Next one was posted to c.l.py.
327
328>>> def gcomb(x, k):
329... "Generate all combinations of k elements from list x."
330...
331... if k > len(x):
332... return
333... if k == 0:
334... yield []
335... else:
336... first, rest = x[0], x[1:]
337... # A combination does or doesn't contain first.
338... # If it does, the remainder is a k-1 comb of rest.
339... for c in gcomb(rest, k-1):
340... c.insert(0, first)
341... yield c
342... # If it doesn't contain first, it's a k comb of rest.
343... for c in gcomb(rest, k):
344... yield c
345
346>>> seq = range(1, 5)
347>>> for k in range(len(seq) + 2):
348... print "%d-combs of %s:" % (k, seq)
349... for c in gcomb(seq, k):
350... print " ", c
3510-combs of [1, 2, 3, 4]:
352 []
3531-combs of [1, 2, 3, 4]:
354 [1]
355 [2]
356 [3]
357 [4]
3582-combs of [1, 2, 3, 4]:
359 [1, 2]
360 [1, 3]
361 [1, 4]
362 [2, 3]
363 [2, 4]
364 [3, 4]
3653-combs of [1, 2, 3, 4]:
366 [1, 2, 3]
367 [1, 2, 4]
368 [1, 3, 4]
369 [2, 3, 4]
3704-combs of [1, 2, 3, 4]:
371 [1, 2, 3, 4]
3725-combs of [1, 2, 3, 4]:
Tim Peters3e7b1a02001-06-25 19:46:25 +0000373
Tim Peterse77f2e22001-06-26 22:24:51 +0000374From the Iterators list, about the types of these things.
Tim Peters3e7b1a02001-06-25 19:46:25 +0000375
376>>> def g():
377... yield 1
378...
379>>> type(g)
380<type 'function'>
381>>> i = g()
382>>> type(i)
383<type 'generator'>
Tim Peters5d2b77c2001-09-03 05:47:38 +0000384>>> [s for s in dir(i) if not s.startswith('_')]
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000385['close', 'gi_frame', 'gi_running', 'next', 'send', 'throw']
Tim Peters3e7b1a02001-06-25 19:46:25 +0000386>>> print i.next.__doc__
Tim Peters6d6c1a32001-08-02 04:15:00 +0000387x.next() -> the next value, or raise StopIteration
Tim Peters3e7b1a02001-06-25 19:46:25 +0000388>>> iter(i) is i
Guido van Rossum77f6a652002-04-03 22:41:51 +0000389True
Tim Peters3e7b1a02001-06-25 19:46:25 +0000390>>> import types
391>>> isinstance(i, types.GeneratorType)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000392True
Tim Peterse77f2e22001-06-26 22:24:51 +0000393
394And more, added later.
395
396>>> i.gi_running
3970
398>>> type(i.gi_frame)
399<type 'frame'>
400>>> i.gi_running = 42
401Traceback (most recent call last):
402 ...
Guido van Rossum61cf7802001-08-10 21:25:24 +0000403TypeError: readonly attribute
Tim Peterse77f2e22001-06-26 22:24:51 +0000404>>> def g():
405... yield me.gi_running
406>>> me = g()
407>>> me.gi_running
4080
409>>> me.next()
4101
411>>> me.gi_running
4120
Tim Peters35302662001-07-02 01:38:33 +0000413
414A clever union-find implementation from c.l.py, due to David Eppstein.
415Sent: Friday, June 29, 2001 12:16 PM
416To: python-list@python.org
417Subject: Re: PEP 255: Simple Generators
418
419>>> class disjointSet:
420... def __init__(self, name):
421... self.name = name
422... self.parent = None
423... self.generator = self.generate()
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000424... self.close = self.generator.close
Tim Peters35302662001-07-02 01:38:33 +0000425...
426... def generate(self):
427... while not self.parent:
428... yield self
429... for x in self.parent.generator:
430... yield x
431...
432... def find(self):
433... return self.generator.next()
434...
435... def union(self, parent):
436... if self.parent:
437... raise ValueError("Sorry, I'm not a root!")
438... self.parent = parent
439...
440... def __str__(self):
441... return self.name
Tim Peters35302662001-07-02 01:38:33 +0000442
443>>> names = "ABCDEFGHIJKLM"
444>>> sets = [disjointSet(name) for name in names]
445>>> roots = sets[:]
446
447>>> import random
Raymond Hettingerdd24a9f2002-12-30 00:46:09 +0000448>>> gen = random.WichmannHill(42)
Tim Peters35302662001-07-02 01:38:33 +0000449>>> while 1:
450... for s in sets:
451... print "%s->%s" % (s, s.find()),
452... print
453... if len(roots) > 1:
Raymond Hettingerdd24a9f2002-12-30 00:46:09 +0000454... s1 = gen.choice(roots)
Tim Peters35302662001-07-02 01:38:33 +0000455... roots.remove(s1)
Raymond Hettingerdd24a9f2002-12-30 00:46:09 +0000456... s2 = gen.choice(roots)
Tim Peters35302662001-07-02 01:38:33 +0000457... s1.union(s2)
458... print "merged", s1, "into", s2
459... else:
460... break
461A->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
462merged D into G
463A->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
464merged C into F
465A->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
466merged L into A
467A->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
468merged H into E
469A->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
470merged B into E
471A->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
472merged J into G
473A->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
474merged E into G
475A->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
476merged M into G
477A->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
478merged I into K
479A->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
480merged K into A
481A->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
482merged F into A
483A->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
484merged A into G
485A->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
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000486
Tim Peterse9fe7e02005-08-07 03:04:58 +0000487>>> for s in sets: s.close() # break cycles
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000488
Tim Peters6ba5f792001-06-23 20:45:43 +0000489"""
Barry Warsaw04f357c2002-07-23 19:04:11 +0000490# Emacs turd '
Tim Peters6ba5f792001-06-23 20:45:43 +0000491
Tim Peters0f9da0a2001-06-23 21:01:47 +0000492# Fun tests (for sufficiently warped notions of "fun").
493
494fun_tests = """
495
496Build up to a recursive Sieve of Eratosthenes generator.
497
498>>> def firstn(g, n):
499... return [g.next() for i in range(n)]
500
501>>> def intsfrom(i):
502... while 1:
503... yield i
504... i += 1
505
506>>> firstn(intsfrom(5), 7)
507[5, 6, 7, 8, 9, 10, 11]
508
509>>> def exclude_multiples(n, ints):
510... for i in ints:
511... if i % n:
512... yield i
513
514>>> firstn(exclude_multiples(3, intsfrom(1)), 6)
515[1, 2, 4, 5, 7, 8]
516
517>>> def sieve(ints):
518... prime = ints.next()
519... yield prime
520... not_divisible_by_prime = exclude_multiples(prime, ints)
521... for p in sieve(not_divisible_by_prime):
522... yield p
523
524>>> primes = sieve(intsfrom(2))
525>>> firstn(primes, 20)
526[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
Tim Petersb9e9ff12001-06-24 03:44:52 +0000527
Tim Petersf6ed0742001-06-27 07:17:57 +0000528
Tim Petersb9e9ff12001-06-24 03:44:52 +0000529Another famous problem: generate all integers of the form
530 2**i * 3**j * 5**k
531in increasing order, where i,j,k >= 0. Trickier than it may look at first!
532Try writing it without generators, and correctly, and without generating
5333 internal results for each result output.
534
535>>> def times(n, g):
536... for i in g:
537... yield n * i
538>>> firstn(times(10, intsfrom(1)), 10)
539[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
540
541>>> def merge(g, h):
542... ng = g.next()
543... nh = h.next()
544... while 1:
545... if ng < nh:
546... yield ng
547... ng = g.next()
548... elif ng > nh:
549... yield nh
550... nh = h.next()
551... else:
552... yield ng
553... ng = g.next()
554... nh = h.next()
555
Tim Petersf6ed0742001-06-27 07:17:57 +0000556The following works, but is doing a whale of a lot of redundant work --
557it's not clear how to get the internal uses of m235 to share a single
558generator. Note that me_times2 (etc) each need to see every element in the
559result sequence. So this is an example where lazy lists are more natural
560(you can look at the head of a lazy list any number of times).
Tim Petersb9e9ff12001-06-24 03:44:52 +0000561
562>>> def m235():
563... yield 1
564... me_times2 = times(2, m235())
565... me_times3 = times(3, m235())
566... me_times5 = times(5, m235())
567... for i in merge(merge(me_times2,
568... me_times3),
569... me_times5):
570... yield i
571
Tim Petersf6ed0742001-06-27 07:17:57 +0000572Don't print "too many" of these -- the implementation above is extremely
573inefficient: each call of m235() leads to 3 recursive calls, and in
574turn each of those 3 more, and so on, and so on, until we've descended
575enough levels to satisfy the print stmts. Very odd: when I printed 5
576lines of results below, this managed to screw up Win98's malloc in "the
577usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting
578address space, and it *looked* like a very slow leak.
579
Tim Petersb9e9ff12001-06-24 03:44:52 +0000580>>> result = m235()
Tim Petersf6ed0742001-06-27 07:17:57 +0000581>>> for i in range(3):
Tim Petersb9e9ff12001-06-24 03:44:52 +0000582... print firstn(result, 15)
583[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
584[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
585[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
Tim Petersee309272001-06-24 05:47:06 +0000586
587Heh. Here's one way to get a shared list, complete with an excruciating
588namespace renaming trick. The *pretty* part is that the times() and merge()
589functions can be reused as-is, because they only assume their stream
590arguments are iterable -- a LazyList is the same as a generator to times().
591
592>>> class LazyList:
593... def __init__(self, g):
594... self.sofar = []
595... self.fetch = g.next
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000596... self.close = g.close
Tim Petersee309272001-06-24 05:47:06 +0000597...
598... def __getitem__(self, i):
599... sofar, fetch = self.sofar, self.fetch
600... while i >= len(sofar):
601... sofar.append(fetch())
602... return sofar[i]
603
604>>> def m235():
605... yield 1
Tim Petersea2e97a2001-06-24 07:10:02 +0000606... # Gack: m235 below actually refers to a LazyList.
Tim Petersee309272001-06-24 05:47:06 +0000607... me_times2 = times(2, m235)
608... me_times3 = times(3, m235)
609... me_times5 = times(5, m235)
610... for i in merge(merge(me_times2,
611... me_times3),
612... me_times5):
613... yield i
614
Tim Petersf6ed0742001-06-27 07:17:57 +0000615Print as many of these as you like -- *this* implementation is memory-
Neil Schemenauerb20e9db2001-07-12 13:26:41 +0000616efficient.
Tim Petersf6ed0742001-06-27 07:17:57 +0000617
Tim Petersee309272001-06-24 05:47:06 +0000618>>> m235 = LazyList(m235())
619>>> for i in range(5):
620... print [m235[j] for j in range(15*i, 15*(i+1))]
621[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
622[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
623[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
624[200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
625[400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
Tim Petersf6ed0742001-06-27 07:17:57 +0000626
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000627>>> m235.close()
Tim Petersf6ed0742001-06-27 07:17:57 +0000628
629Ye olde Fibonacci generator, LazyList style.
630
631>>> def fibgen(a, b):
632...
633... def sum(g, h):
634... while 1:
635... yield g.next() + h.next()
636...
637... def tail(g):
638... g.next() # throw first away
639... for x in g:
640... yield x
641...
642... yield a
643... yield b
644... for s in sum(iter(fib),
645... tail(iter(fib))):
646... yield s
647
648>>> fib = LazyList(fibgen(1, 2))
649>>> firstn(iter(fib), 17)
650[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000651>>> fib.close()
Tim Peters0f9da0a2001-06-23 21:01:47 +0000652"""
653
Tim Petersb6c3cea2001-06-26 03:36:28 +0000654# syntax_tests mostly provokes SyntaxErrors. Also fiddling with #if 0
655# hackery.
Tim Petersee309272001-06-24 05:47:06 +0000656
Tim Petersea2e97a2001-06-24 07:10:02 +0000657syntax_tests = """
658
Tim Petersaef8cfa2004-08-27 15:12:49 +0000659>>> def f():
Tim Petersea2e97a2001-06-24 07:10:02 +0000660... return 22
661... yield 1
662Traceback (most recent call last):
Tim Peters77dcccc2004-08-27 05:44:51 +0000663 ..
Tim Petersc5684782004-09-13 01:07:12 +0000664SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[0]>, line 2)
Tim Petersea2e97a2001-06-24 07:10:02 +0000665
Tim Petersaef8cfa2004-08-27 15:12:49 +0000666>>> def f():
Tim Petersea2e97a2001-06-24 07:10:02 +0000667... yield 1
668... return 22
669Traceback (most recent call last):
Tim Peters77dcccc2004-08-27 05:44:51 +0000670 ..
Tim Petersc5684782004-09-13 01:07:12 +0000671SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[1]>, line 3)
Tim Petersea2e97a2001-06-24 07:10:02 +0000672
673"return None" is not the same as "return" in a generator:
674
Tim Petersaef8cfa2004-08-27 15:12:49 +0000675>>> def f():
Tim Petersea2e97a2001-06-24 07:10:02 +0000676... yield 1
677... return None
678Traceback (most recent call last):
Tim Peters77dcccc2004-08-27 05:44:51 +0000679 ..
Tim Petersc5684782004-09-13 01:07:12 +0000680SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[2]>, line 3)
Tim Petersea2e97a2001-06-24 07:10:02 +0000681
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000682These are fine:
Tim Petersea2e97a2001-06-24 07:10:02 +0000683
684>>> def f():
685... yield 1
686... return
687
Tim Petersaef8cfa2004-08-27 15:12:49 +0000688>>> def f():
Tim Petersea2e97a2001-06-24 07:10:02 +0000689... try:
690... yield 1
691... finally:
692... pass
Tim Petersea2e97a2001-06-24 07:10:02 +0000693
Tim Petersaef8cfa2004-08-27 15:12:49 +0000694>>> def f():
Tim Petersea2e97a2001-06-24 07:10:02 +0000695... try:
696... try:
Tim Peters3caca232001-12-06 06:23:26 +0000697... 1//0
Tim Petersea2e97a2001-06-24 07:10:02 +0000698... except ZeroDivisionError:
699... yield 666 # bad because *outer* try has finally
700... except:
701... pass
702... finally:
703... pass
Tim Petersea2e97a2001-06-24 07:10:02 +0000704
705>>> def f():
706... try:
707... try:
708... yield 12
Tim Peters3caca232001-12-06 06:23:26 +0000709... 1//0
Tim Petersea2e97a2001-06-24 07:10:02 +0000710... except ZeroDivisionError:
711... yield 666
712... except:
713... try:
714... x = 12
715... finally:
716... yield 12
717... except:
718... return
719>>> list(f())
720[12, 666]
Tim Petersb6c3cea2001-06-26 03:36:28 +0000721
722>>> def f():
Tim Peters08a898f2001-06-28 01:52:22 +0000723... yield
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000724>>> type(f())
725<type 'generator'>
726
Tim Peters08a898f2001-06-28 01:52:22 +0000727
728>>> def f():
729... if 0:
730... yield
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000731>>> type(f())
732<type 'generator'>
733
Tim Peters08a898f2001-06-28 01:52:22 +0000734
735>>> def f():
Tim Petersb6c3cea2001-06-26 03:36:28 +0000736... if 0:
737... yield 1
738>>> type(f())
739<type 'generator'>
740
741>>> def f():
742... if "":
743... yield None
744>>> type(f())
745<type 'generator'>
746
747>>> def f():
748... return
749... try:
750... if x==4:
751... pass
752... elif 0:
753... try:
Tim Peters3caca232001-12-06 06:23:26 +0000754... 1//0
Tim Petersb6c3cea2001-06-26 03:36:28 +0000755... except SyntaxError:
756... pass
757... else:
758... if 0:
759... while 12:
760... x += 1
761... yield 2 # don't blink
762... f(a, b, c, d, e)
763... else:
764... pass
765... except:
766... x = 1
767... return
768>>> type(f())
769<type 'generator'>
770
771>>> def f():
772... if 0:
773... def g():
774... yield 1
775...
776>>> type(f())
Guido van Rossum297abad2001-08-16 08:32:39 +0000777<type 'NoneType'>
Tim Petersb6c3cea2001-06-26 03:36:28 +0000778
779>>> def f():
780... if 0:
781... class C:
782... def __init__(self):
783... yield 1
784... def f(self):
785... yield 2
786>>> type(f())
Guido van Rossum297abad2001-08-16 08:32:39 +0000787<type 'NoneType'>
Tim Peters08a898f2001-06-28 01:52:22 +0000788
789>>> def f():
790... if 0:
791... return
792... if 0:
793... yield 2
794>>> type(f())
795<type 'generator'>
796
797
Tim Petersaef8cfa2004-08-27 15:12:49 +0000798>>> def f():
Tim Peters08a898f2001-06-28 01:52:22 +0000799... if 0:
800... lambda x: x # shouldn't trigger here
801... return # or here
802... def f(i):
803... return 2*i # or here
804... if 0:
805... return 3 # but *this* sucks (line 8)
806... if 0:
807... yield 2 # because it's a generator
808Traceback (most recent call last):
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000809SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[24]>, line 8)
Guido van Rossumc5fe5eb2002-06-12 03:45:21 +0000810
811This one caused a crash (see SF bug 567538):
812
813>>> def f():
814... for i in range(3):
815... try:
816... continue
817... finally:
818... yield i
Tim Petersc411dba2002-07-16 21:35:23 +0000819...
Guido van Rossumc5fe5eb2002-06-12 03:45:21 +0000820>>> g = f()
821>>> print g.next()
8220
823>>> print g.next()
8241
825>>> print g.next()
8262
827>>> print g.next()
828Traceback (most recent call last):
829StopIteration
Tim Petersea2e97a2001-06-24 07:10:02 +0000830"""
831
Tim Petersbe4f0a72001-06-29 02:41:16 +0000832# conjoin is a simple backtracking generator, named in honor of Icon's
833# "conjunction" control structure. Pass a list of no-argument functions
834# that return iterable objects. Easiest to explain by example: assume the
835# function list [x, y, z] is passed. Then conjoin acts like:
836#
837# def g():
838# values = [None] * 3
839# for values[0] in x():
840# for values[1] in y():
841# for values[2] in z():
842# yield values
843#
844# So some 3-lists of values *may* be generated, each time we successfully
845# get into the innermost loop. If an iterator fails (is exhausted) before
846# then, it "backtracks" to get the next value from the nearest enclosing
847# iterator (the one "to the left"), and starts all over again at the next
848# slot (pumps a fresh iterator). Of course this is most useful when the
849# iterators have side-effects, so that which values *can* be generated at
850# each slot depend on the values iterated at previous slots.
851
852def conjoin(gs):
853
854 values = [None] * len(gs)
855
856 def gen(i, values=values):
857 if i >= len(gs):
858 yield values
859 else:
860 for values[i] in gs[i]():
861 for x in gen(i+1):
862 yield x
863
864 for x in gen(0):
865 yield x
866
Tim Petersc468fd22001-06-30 07:29:44 +0000867# That works fine, but recursing a level and checking i against len(gs) for
868# each item produced is inefficient. By doing manual loop unrolling across
869# generator boundaries, it's possible to eliminate most of that overhead.
870# This isn't worth the bother *in general* for generators, but conjoin() is
871# a core building block for some CPU-intensive generator applications.
872
873def conjoin(gs):
874
875 n = len(gs)
876 values = [None] * n
877
878 # Do one loop nest at time recursively, until the # of loop nests
879 # remaining is divisible by 3.
880
881 def gen(i, values=values):
882 if i >= n:
883 yield values
884
885 elif (n-i) % 3:
886 ip1 = i+1
887 for values[i] in gs[i]():
888 for x in gen(ip1):
889 yield x
890
891 else:
892 for x in _gen3(i):
893 yield x
894
895 # Do three loop nests at a time, recursing only if at least three more
896 # remain. Don't call directly: this is an internal optimization for
897 # gen's use.
898
899 def _gen3(i, values=values):
900 assert i < n and (n-i) % 3 == 0
901 ip1, ip2, ip3 = i+1, i+2, i+3
902 g, g1, g2 = gs[i : ip3]
903
904 if ip3 >= n:
905 # These are the last three, so we can yield values directly.
906 for values[i] in g():
907 for values[ip1] in g1():
908 for values[ip2] in g2():
909 yield values
910
911 else:
912 # At least 6 loop nests remain; peel off 3 and recurse for the
913 # rest.
914 for values[i] in g():
915 for values[ip1] in g1():
916 for values[ip2] in g2():
917 for x in _gen3(ip3):
918 yield x
919
920 for x in gen(0):
921 yield x
922
unknown31569562001-07-04 22:11:22 +0000923# And one more approach: For backtracking apps like the Knight's Tour
924# solver below, the number of backtracking levels can be enormous (one
925# level per square, for the Knight's Tour, so that e.g. a 100x100 board
926# needs 10,000 levels). In such cases Python is likely to run out of
927# stack space due to recursion. So here's a recursion-free version of
928# conjoin too.
929# NOTE WELL: This allows large problems to be solved with only trivial
930# demands on stack space. Without explicitly resumable generators, this is
Tim Peters9a8c8e22001-07-13 09:12:12 +0000931# much harder to achieve. OTOH, this is much slower (up to a factor of 2)
932# than the fancy unrolled recursive conjoin.
unknown31569562001-07-04 22:11:22 +0000933
934def flat_conjoin(gs): # rename to conjoin to run tests with this instead
935 n = len(gs)
936 values = [None] * n
937 iters = [None] * n
Tim Peters9a8c8e22001-07-13 09:12:12 +0000938 _StopIteration = StopIteration # make local because caught a *lot*
unknown31569562001-07-04 22:11:22 +0000939 i = 0
Tim Peters9a8c8e22001-07-13 09:12:12 +0000940 while 1:
941 # Descend.
942 try:
943 while i < n:
944 it = iters[i] = gs[i]().next
945 values[i] = it()
946 i += 1
947 except _StopIteration:
948 pass
unknown31569562001-07-04 22:11:22 +0000949 else:
Tim Peters9a8c8e22001-07-13 09:12:12 +0000950 assert i == n
951 yield values
unknown31569562001-07-04 22:11:22 +0000952
Tim Peters9a8c8e22001-07-13 09:12:12 +0000953 # Backtrack until an older iterator can be resumed.
954 i -= 1
unknown31569562001-07-04 22:11:22 +0000955 while i >= 0:
956 try:
957 values[i] = iters[i]()
Tim Peters9a8c8e22001-07-13 09:12:12 +0000958 # Success! Start fresh at next level.
unknown31569562001-07-04 22:11:22 +0000959 i += 1
960 break
Tim Peters9a8c8e22001-07-13 09:12:12 +0000961 except _StopIteration:
962 # Continue backtracking.
963 i -= 1
964 else:
965 assert i < 0
966 break
unknown31569562001-07-04 22:11:22 +0000967
Tim Petersbe4f0a72001-06-29 02:41:16 +0000968# A conjoin-based N-Queens solver.
969
970class Queens:
971 def __init__(self, n):
972 self.n = n
973 rangen = range(n)
974
975 # Assign a unique int to each column and diagonal.
976 # columns: n of those, range(n).
977 # NW-SE diagonals: 2n-1 of these, i-j unique and invariant along
978 # each, smallest i-j is 0-(n-1) = 1-n, so add n-1 to shift to 0-
979 # based.
980 # NE-SW diagonals: 2n-1 of these, i+j unique and invariant along
981 # each, smallest i+j is 0, largest is 2n-2.
982
983 # For each square, compute a bit vector of the columns and
984 # diagonals it covers, and for each row compute a function that
985 # generates the possiblities for the columns in that row.
986 self.rowgenerators = []
987 for i in rangen:
988 rowuses = [(1L << j) | # column ordinal
989 (1L << (n + i-j + n-1)) | # NW-SE ordinal
990 (1L << (n + 2*n-1 + i+j)) # NE-SW ordinal
991 for j in rangen]
992
993 def rowgen(rowuses=rowuses):
994 for j in rangen:
995 uses = rowuses[j]
Tim Petersc468fd22001-06-30 07:29:44 +0000996 if uses & self.used == 0:
997 self.used |= uses
998 yield j
999 self.used &= ~uses
Tim Petersbe4f0a72001-06-29 02:41:16 +00001000
1001 self.rowgenerators.append(rowgen)
1002
1003 # Generate solutions.
1004 def solve(self):
1005 self.used = 0
1006 for row2col in conjoin(self.rowgenerators):
1007 yield row2col
1008
1009 def printsolution(self, row2col):
1010 n = self.n
1011 assert n == len(row2col)
1012 sep = "+" + "-+" * n
1013 print sep
1014 for i in range(n):
1015 squares = [" " for j in range(n)]
1016 squares[row2col[i]] = "Q"
1017 print "|" + "|".join(squares) + "|"
1018 print sep
1019
unknown31569562001-07-04 22:11:22 +00001020# A conjoin-based Knight's Tour solver. This is pretty sophisticated
1021# (e.g., when used with flat_conjoin above, and passing hard=1 to the
1022# constructor, a 200x200 Knight's Tour was found quickly -- note that we're
Tim Peters9a8c8e22001-07-13 09:12:12 +00001023# creating 10s of thousands of generators then!), and is lengthy.
unknown31569562001-07-04 22:11:22 +00001024
1025class Knights:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001026 def __init__(self, m, n, hard=0):
1027 self.m, self.n = m, n
unknown31569562001-07-04 22:11:22 +00001028
Tim Peters9a8c8e22001-07-13 09:12:12 +00001029 # solve() will set up succs[i] to be a list of square #i's
1030 # successors.
1031 succs = self.succs = []
unknown31569562001-07-04 22:11:22 +00001032
Tim Peters9a8c8e22001-07-13 09:12:12 +00001033 # Remove i0 from each of its successor's successor lists, i.e.
1034 # successors can't go back to i0 again. Return 0 if we can
1035 # detect this makes a solution impossible, else return 1.
unknown31569562001-07-04 22:11:22 +00001036
Tim Peters9a8c8e22001-07-13 09:12:12 +00001037 def remove_from_successors(i0, len=len):
unknown31569562001-07-04 22:11:22 +00001038 # If we remove all exits from a free square, we're dead:
1039 # even if we move to it next, we can't leave it again.
1040 # If we create a square with one exit, we must visit it next;
1041 # else somebody else will have to visit it, and since there's
1042 # only one adjacent, there won't be a way to leave it again.
1043 # Finelly, if we create more than one free square with a
1044 # single exit, we can only move to one of them next, leaving
1045 # the other one a dead end.
1046 ne0 = ne1 = 0
1047 for i in succs[i0]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001048 s = succs[i]
1049 s.remove(i0)
1050 e = len(s)
1051 if e == 0:
1052 ne0 += 1
1053 elif e == 1:
1054 ne1 += 1
unknown31569562001-07-04 22:11:22 +00001055 return ne0 == 0 and ne1 < 2
1056
Tim Peters9a8c8e22001-07-13 09:12:12 +00001057 # Put i0 back in each of its successor's successor lists.
1058
1059 def add_to_successors(i0):
unknown31569562001-07-04 22:11:22 +00001060 for i in succs[i0]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001061 succs[i].append(i0)
unknown31569562001-07-04 22:11:22 +00001062
1063 # Generate the first move.
1064 def first():
Tim Peters9a8c8e22001-07-13 09:12:12 +00001065 if m < 1 or n < 1:
unknown31569562001-07-04 22:11:22 +00001066 return
1067
unknown31569562001-07-04 22:11:22 +00001068 # Since we're looking for a cycle, it doesn't matter where we
1069 # start. Starting in a corner makes the 2nd move easy.
Tim Peters9a8c8e22001-07-13 09:12:12 +00001070 corner = self.coords2index(0, 0)
1071 remove_from_successors(corner)
unknown31569562001-07-04 22:11:22 +00001072 self.lastij = corner
1073 yield corner
Tim Peters9a8c8e22001-07-13 09:12:12 +00001074 add_to_successors(corner)
unknown31569562001-07-04 22:11:22 +00001075
1076 # Generate the second moves.
1077 def second():
Tim Peters9a8c8e22001-07-13 09:12:12 +00001078 corner = self.coords2index(0, 0)
unknown31569562001-07-04 22:11:22 +00001079 assert self.lastij == corner # i.e., we started in the corner
Tim Peters9a8c8e22001-07-13 09:12:12 +00001080 if m < 3 or n < 3:
unknown31569562001-07-04 22:11:22 +00001081 return
Tim Peters9a8c8e22001-07-13 09:12:12 +00001082 assert len(succs[corner]) == 2
1083 assert self.coords2index(1, 2) in succs[corner]
1084 assert self.coords2index(2, 1) in succs[corner]
unknown31569562001-07-04 22:11:22 +00001085 # Only two choices. Whichever we pick, the other must be the
Tim Peters9a8c8e22001-07-13 09:12:12 +00001086 # square picked on move m*n, as it's the only way to get back
unknown31569562001-07-04 22:11:22 +00001087 # to (0, 0). Save its index in self.final so that moves before
1088 # the last know it must be kept free.
1089 for i, j in (1, 2), (2, 1):
Tim Peters9a8c8e22001-07-13 09:12:12 +00001090 this = self.coords2index(i, j)
1091 final = self.coords2index(3-i, 3-j)
unknown31569562001-07-04 22:11:22 +00001092 self.final = final
unknown31569562001-07-04 22:11:22 +00001093
Tim Peters9a8c8e22001-07-13 09:12:12 +00001094 remove_from_successors(this)
1095 succs[final].append(corner)
unknown31569562001-07-04 22:11:22 +00001096 self.lastij = this
1097 yield this
Tim Peters9a8c8e22001-07-13 09:12:12 +00001098 succs[final].remove(corner)
1099 add_to_successors(this)
unknown31569562001-07-04 22:11:22 +00001100
Tim Peters9a8c8e22001-07-13 09:12:12 +00001101 # Generate moves 3 thru m*n-1.
1102 def advance(len=len):
unknown31569562001-07-04 22:11:22 +00001103 # If some successor has only one exit, must take it.
1104 # Else favor successors with fewer exits.
1105 candidates = []
1106 for i in succs[self.lastij]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001107 e = len(succs[i])
1108 assert e > 0, "else remove_from_successors() pruning flawed"
1109 if e == 1:
1110 candidates = [(e, i)]
1111 break
1112 candidates.append((e, i))
unknown31569562001-07-04 22:11:22 +00001113 else:
1114 candidates.sort()
1115
1116 for e, i in candidates:
1117 if i != self.final:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001118 if remove_from_successors(i):
unknown31569562001-07-04 22:11:22 +00001119 self.lastij = i
1120 yield i
Tim Peters9a8c8e22001-07-13 09:12:12 +00001121 add_to_successors(i)
unknown31569562001-07-04 22:11:22 +00001122
Tim Peters9a8c8e22001-07-13 09:12:12 +00001123 # Generate moves 3 thru m*n-1. Alternative version using a
unknown31569562001-07-04 22:11:22 +00001124 # stronger (but more expensive) heuristic to order successors.
Tim Peters9a8c8e22001-07-13 09:12:12 +00001125 # Since the # of backtracking levels is m*n, a poor move early on
1126 # can take eons to undo. Smallest square board for which this
1127 # matters a lot is 52x52.
1128 def advance_hard(vmid=(m-1)/2.0, hmid=(n-1)/2.0, len=len):
unknown31569562001-07-04 22:11:22 +00001129 # If some successor has only one exit, must take it.
1130 # Else favor successors with fewer exits.
1131 # Break ties via max distance from board centerpoint (favor
1132 # corners and edges whenever possible).
1133 candidates = []
1134 for i in succs[self.lastij]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001135 e = len(succs[i])
1136 assert e > 0, "else remove_from_successors() pruning flawed"
1137 if e == 1:
1138 candidates = [(e, 0, i)]
1139 break
1140 i1, j1 = self.index2coords(i)
1141 d = (i1 - vmid)**2 + (j1 - hmid)**2
1142 candidates.append((e, -d, i))
unknown31569562001-07-04 22:11:22 +00001143 else:
1144 candidates.sort()
1145
1146 for e, d, i in candidates:
1147 if i != self.final:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001148 if remove_from_successors(i):
unknown31569562001-07-04 22:11:22 +00001149 self.lastij = i
1150 yield i
Tim Peters9a8c8e22001-07-13 09:12:12 +00001151 add_to_successors(i)
unknown31569562001-07-04 22:11:22 +00001152
1153 # Generate the last move.
1154 def last():
1155 assert self.final in succs[self.lastij]
1156 yield self.final
1157
Tim Peters9a8c8e22001-07-13 09:12:12 +00001158 if m*n < 4:
1159 self.squaregenerators = [first]
unknown31569562001-07-04 22:11:22 +00001160 else:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001161 self.squaregenerators = [first, second] + \
1162 [hard and advance_hard or advance] * (m*n - 3) + \
unknown31569562001-07-04 22:11:22 +00001163 [last]
1164
Tim Peters9a8c8e22001-07-13 09:12:12 +00001165 def coords2index(self, i, j):
1166 assert 0 <= i < self.m
1167 assert 0 <= j < self.n
1168 return i * self.n + j
1169
1170 def index2coords(self, index):
1171 assert 0 <= index < self.m * self.n
1172 return divmod(index, self.n)
1173
1174 def _init_board(self):
1175 succs = self.succs
1176 del succs[:]
1177 m, n = self.m, self.n
1178 c2i = self.coords2index
1179
1180 offsets = [( 1, 2), ( 2, 1), ( 2, -1), ( 1, -2),
1181 (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
1182 rangen = range(n)
1183 for i in range(m):
1184 for j in rangen:
1185 s = [c2i(i+io, j+jo) for io, jo in offsets
1186 if 0 <= i+io < m and
1187 0 <= j+jo < n]
1188 succs.append(s)
1189
unknown31569562001-07-04 22:11:22 +00001190 # Generate solutions.
1191 def solve(self):
Tim Peters9a8c8e22001-07-13 09:12:12 +00001192 self._init_board()
1193 for x in conjoin(self.squaregenerators):
unknown31569562001-07-04 22:11:22 +00001194 yield x
1195
1196 def printsolution(self, x):
Tim Peters9a8c8e22001-07-13 09:12:12 +00001197 m, n = self.m, self.n
1198 assert len(x) == m*n
1199 w = len(str(m*n))
unknown31569562001-07-04 22:11:22 +00001200 format = "%" + str(w) + "d"
1201
Tim Peters9a8c8e22001-07-13 09:12:12 +00001202 squares = [[None] * n for i in range(m)]
unknown31569562001-07-04 22:11:22 +00001203 k = 1
1204 for i in x:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001205 i1, j1 = self.index2coords(i)
unknown31569562001-07-04 22:11:22 +00001206 squares[i1][j1] = format % k
1207 k += 1
1208
1209 sep = "+" + ("-" * w + "+") * n
1210 print sep
Tim Peters9a8c8e22001-07-13 09:12:12 +00001211 for i in range(m):
unknown31569562001-07-04 22:11:22 +00001212 row = squares[i]
1213 print "|" + "|".join(row) + "|"
1214 print sep
1215
Tim Petersbe4f0a72001-06-29 02:41:16 +00001216conjoin_tests = """
1217
1218Generate the 3-bit binary numbers in order. This illustrates dumbest-
1219possible use of conjoin, just to generate the full cross-product.
1220
unknown31569562001-07-04 22:11:22 +00001221>>> for c in conjoin([lambda: iter((0, 1))] * 3):
Tim Petersbe4f0a72001-06-29 02:41:16 +00001222... print c
1223[0, 0, 0]
1224[0, 0, 1]
1225[0, 1, 0]
1226[0, 1, 1]
1227[1, 0, 0]
1228[1, 0, 1]
1229[1, 1, 0]
1230[1, 1, 1]
1231
Tim Petersc468fd22001-06-30 07:29:44 +00001232For efficiency in typical backtracking apps, conjoin() yields the same list
1233object each time. So if you want to save away a full account of its
1234generated sequence, you need to copy its results.
1235
1236>>> def gencopy(iterator):
1237... for x in iterator:
1238... yield x[:]
1239
1240>>> for n in range(10):
unknown31569562001-07-04 22:11:22 +00001241... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n)))
Tim Petersc468fd22001-06-30 07:29:44 +00001242... print n, len(all), all[0] == [0] * n, all[-1] == [1] * n
Guido van Rossum77f6a652002-04-03 22:41:51 +000012430 1 True True
12441 2 True True
12452 4 True True
12463 8 True True
12474 16 True True
12485 32 True True
12496 64 True True
12507 128 True True
12518 256 True True
12529 512 True True
Tim Petersc468fd22001-06-30 07:29:44 +00001253
Tim Petersbe4f0a72001-06-29 02:41:16 +00001254And run an 8-queens solver.
1255
1256>>> q = Queens(8)
1257>>> LIMIT = 2
1258>>> count = 0
1259>>> for row2col in q.solve():
1260... count += 1
1261... if count <= LIMIT:
1262... print "Solution", count
1263... q.printsolution(row2col)
1264Solution 1
1265+-+-+-+-+-+-+-+-+
1266|Q| | | | | | | |
1267+-+-+-+-+-+-+-+-+
1268| | | | |Q| | | |
1269+-+-+-+-+-+-+-+-+
1270| | | | | | | |Q|
1271+-+-+-+-+-+-+-+-+
1272| | | | | |Q| | |
1273+-+-+-+-+-+-+-+-+
1274| | |Q| | | | | |
1275+-+-+-+-+-+-+-+-+
1276| | | | | | |Q| |
1277+-+-+-+-+-+-+-+-+
1278| |Q| | | | | | |
1279+-+-+-+-+-+-+-+-+
1280| | | |Q| | | | |
1281+-+-+-+-+-+-+-+-+
1282Solution 2
1283+-+-+-+-+-+-+-+-+
1284|Q| | | | | | | |
1285+-+-+-+-+-+-+-+-+
1286| | | | | |Q| | |
1287+-+-+-+-+-+-+-+-+
1288| | | | | | | |Q|
1289+-+-+-+-+-+-+-+-+
1290| | |Q| | | | | |
1291+-+-+-+-+-+-+-+-+
1292| | | | | | |Q| |
1293+-+-+-+-+-+-+-+-+
1294| | | |Q| | | | |
1295+-+-+-+-+-+-+-+-+
1296| |Q| | | | | | |
1297+-+-+-+-+-+-+-+-+
1298| | | | |Q| | | |
1299+-+-+-+-+-+-+-+-+
1300
1301>>> print count, "solutions in all."
130292 solutions in all.
unknown31569562001-07-04 22:11:22 +00001303
1304And run a Knight's Tour on a 10x10 board. Note that there are about
130520,000 solutions even on a 6x6 board, so don't dare run this to exhaustion.
1306
Tim Peters9a8c8e22001-07-13 09:12:12 +00001307>>> k = Knights(10, 10)
unknown31569562001-07-04 22:11:22 +00001308>>> LIMIT = 2
1309>>> count = 0
1310>>> for x in k.solve():
1311... count += 1
1312... if count <= LIMIT:
1313... print "Solution", count
1314... k.printsolution(x)
1315... else:
1316... break
1317Solution 1
1318+---+---+---+---+---+---+---+---+---+---+
1319| 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
1320+---+---+---+---+---+---+---+---+---+---+
1321| 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
1322+---+---+---+---+---+---+---+---+---+---+
1323| 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
1324+---+---+---+---+---+---+---+---+---+---+
1325| 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
1326+---+---+---+---+---+---+---+---+---+---+
1327| 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
1328+---+---+---+---+---+---+---+---+---+---+
1329| 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
1330+---+---+---+---+---+---+---+---+---+---+
1331| 87| 98| 91| 80| 77| 84| 53| 46| 65| 44|
1332+---+---+---+---+---+---+---+---+---+---+
1333| 90| 23| 88| 95| 70| 79| 68| 83| 14| 17|
1334+---+---+---+---+---+---+---+---+---+---+
1335| 97| 92| 21| 78| 81| 94| 19| 16| 45| 66|
1336+---+---+---+---+---+---+---+---+---+---+
1337| 22| 89| 96| 93| 20| 69| 82| 67| 18| 15|
1338+---+---+---+---+---+---+---+---+---+---+
1339Solution 2
1340+---+---+---+---+---+---+---+---+---+---+
1341| 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
1342+---+---+---+---+---+---+---+---+---+---+
1343| 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
1344+---+---+---+---+---+---+---+---+---+---+
1345| 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
1346+---+---+---+---+---+---+---+---+---+---+
1347| 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
1348+---+---+---+---+---+---+---+---+---+---+
1349| 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
1350+---+---+---+---+---+---+---+---+---+---+
1351| 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
1352+---+---+---+---+---+---+---+---+---+---+
1353| 87| 98| 89| 80| 77| 84| 53| 46| 65| 44|
1354+---+---+---+---+---+---+---+---+---+---+
1355| 90| 23| 92| 95| 70| 79| 68| 83| 14| 17|
1356+---+---+---+---+---+---+---+---+---+---+
1357| 97| 88| 21| 78| 81| 94| 19| 16| 45| 66|
1358+---+---+---+---+---+---+---+---+---+---+
1359| 22| 91| 96| 93| 20| 69| 82| 67| 18| 15|
1360+---+---+---+---+---+---+---+---+---+---+
Tim Petersbe4f0a72001-06-29 02:41:16 +00001361"""
1362
Fred Drake56d12662002-08-09 18:37:10 +00001363weakref_tests = """\
1364Generators are weakly referencable:
1365
1366>>> import weakref
1367>>> def gen():
1368... yield 'foo!'
1369...
1370>>> wr = weakref.ref(gen)
1371>>> wr() is gen
1372True
1373>>> p = weakref.proxy(gen)
1374
1375Generator-iterators are weakly referencable as well:
1376
1377>>> gi = gen()
1378>>> wr = weakref.ref(gi)
1379>>> wr() is gi
1380True
1381>>> p = weakref.proxy(gi)
1382>>> list(p)
1383['foo!']
1384
1385"""
1386
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00001387coroutine_tests = """\
1388Sending a value into a started generator:
1389
1390>>> def f():
1391... print (yield 1)
1392... yield 2
1393>>> g = f()
1394>>> g.next()
13951
1396>>> g.send(42)
139742
13982
1399
1400Sending a value into a new generator produces a TypeError:
1401
1402>>> f().send("foo")
1403Traceback (most recent call last):
1404...
1405TypeError: can't send non-None value to a just-started generator
1406
1407
1408Yield by itself yields None:
1409
1410>>> def f(): yield
1411>>> list(f())
1412[None]
1413
1414
1415
1416An obscene abuse of a yield expression within a generator expression:
1417
1418>>> list((yield 21) for i in range(4))
1419[21, None, 21, None, 21, None, 21, None]
1420
1421And a more sane, but still weird usage:
1422
1423>>> def f(): list(i for i in [(yield 26)])
1424>>> type(f())
1425<type 'generator'>
1426
1427
1428Check some syntax errors for yield expressions:
1429
1430>>> f=lambda: (yield 1),(yield 2)
1431Traceback (most recent call last):
1432 ...
1433SyntaxError: 'yield' outside function (<doctest test.test_generators.__test__.coroutine[10]>, line 1)
1434
1435>>> def f(): return lambda x=(yield): 1
1436Traceback (most recent call last):
1437 ...
1438SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.coroutine[11]>, line 1)
1439
1440>>> def f(): x = yield = y
1441Traceback (most recent call last):
1442 ...
1443SyntaxError: assignment to yield expression not possible (<doctest test.test_generators.__test__.coroutine[12]>, line 1)
1444
1445
1446Now check some throw() conditions:
1447
1448>>> def f():
1449... while True:
1450... try:
1451... print (yield)
1452... except ValueError,v:
1453... print "caught ValueError (%s)" % (v),
1454>>> import sys
1455>>> g = f()
1456>>> g.next()
1457
1458>>> g.throw(ValueError) # type only
1459caught ValueError ()
1460
1461>>> g.throw(ValueError("xyz")) # value only
1462caught ValueError (xyz)
1463
1464>>> g.throw(ValueError, ValueError(1)) # value+matching type
1465caught ValueError (1)
1466
1467>>> g.throw(ValueError, TypeError(1)) # mismatched type, rewrapped
1468caught ValueError (1)
1469
Tim Peterse9fe7e02005-08-07 03:04:58 +00001470>>> g.throw(ValueError(1), "foo") # bad args
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00001471Traceback (most recent call last):
1472 ...
1473TypeError: instance exception may not have a separate value
1474
Tim Peterse9fe7e02005-08-07 03:04:58 +00001475>>> g.throw(ValueError, "foo", 23) # bad args
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00001476Traceback (most recent call last):
1477 ...
1478TypeError: throw() third argument must be a traceback object
1479
1480>>> def throw(g,exc):
1481... try:
1482... raise exc
1483... except:
1484... g.throw(*sys.exc_info())
Tim Peterse9fe7e02005-08-07 03:04:58 +00001485>>> throw(g,ValueError) # do it with traceback included
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00001486caught ValueError ()
1487
1488>>> g.send(1)
14891
1490
Tim Peterse9fe7e02005-08-07 03:04:58 +00001491>>> throw(g,TypeError) # terminate the generator
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00001492Traceback (most recent call last):
1493 ...
1494TypeError
1495
1496>>> print g.gi_frame
1497None
1498
1499>>> g.send(2)
1500Traceback (most recent call last):
1501 ...
1502StopIteration
1503
Tim Peterse9fe7e02005-08-07 03:04:58 +00001504>>> g.throw(ValueError,6) # throw on closed generator
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00001505Traceback (most recent call last):
1506 ...
1507ValueError: 6
1508
Tim Peterse9fe7e02005-08-07 03:04:58 +00001509>>> f().throw(ValueError,7) # throw on just-opened generator
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00001510Traceback (most recent call last):
1511 ...
1512ValueError: 7
1513
1514
1515Now let's try closing a generator:
1516
1517>>> def f():
1518... try: yield
1519... except GeneratorExit:
1520... print "exiting"
1521
1522>>> g = f()
1523>>> g.next()
1524>>> g.close()
1525exiting
1526>>> g.close() # should be no-op now
1527
1528>>> f().close() # close on just-opened generator should be fine
1529
Tim Peterse9fe7e02005-08-07 03:04:58 +00001530>>> def f(): yield # an even simpler generator
1531>>> f().close() # close before opening
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00001532>>> g = f()
1533>>> g.next()
Tim Peterse9fe7e02005-08-07 03:04:58 +00001534>>> g.close() # close normally
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00001535
1536And finalization:
1537
1538>>> def f():
1539... try: yield
1540... finally:
1541... print "exiting"
1542
1543>>> g = f()
1544>>> g.next()
1545>>> del g
1546exiting
1547
1548
1549Now let's try some ill-behaved generators:
1550
1551>>> def f():
1552... try: yield
1553... except GeneratorExit:
1554... yield "foo!"
1555>>> g = f()
1556>>> g.next()
1557>>> g.close()
1558Traceback (most recent call last):
1559 ...
1560RuntimeError: generator ignored GeneratorExit
1561>>> g.close()
1562
1563
1564Our ill-behaved code should be invoked during GC:
1565
1566>>> import sys, StringIO
1567>>> old, sys.stderr = sys.stderr, StringIO.StringIO()
1568>>> g = f()
1569>>> g.next()
1570>>> del g
1571>>> sys.stderr.getvalue().startswith(
1572... "Exception exceptions.RuntimeError: 'generator ignored GeneratorExit' in "
1573... )
1574True
1575>>> sys.stderr = old
1576
1577
1578And errors thrown during closing should propagate:
1579
1580>>> def f():
1581... try: yield
1582... except GeneratorExit:
1583... raise TypeError("fie!")
1584>>> g = f()
1585>>> g.next()
1586>>> g.close()
1587Traceback (most recent call last):
1588 ...
1589TypeError: fie!
1590
1591
1592Ensure that various yield expression constructs make their
1593enclosing function a generator:
1594
1595>>> def f(): x += yield
1596>>> type(f())
1597<type 'generator'>
1598
1599>>> def f(): x = yield
1600>>> type(f())
1601<type 'generator'>
1602
1603>>> def f(): lambda x=(yield): 1
1604>>> type(f())
1605<type 'generator'>
1606
1607>>> def f(): x=(i for i in (yield) if (yield))
1608>>> type(f())
1609<type 'generator'>
1610
1611>>> def f(d): d[(yield "a")] = d[(yield "b")] = 27
1612>>> data = [1,2]
1613>>> g = f(data)
1614>>> type(g)
1615<type 'generator'>
1616>>> g.send(None)
1617'a'
1618>>> data
1619[1, 2]
1620>>> g.send(0)
1621'b'
1622>>> data
1623[27, 2]
1624>>> try: g.send(1)
1625... except StopIteration: pass
1626>>> data
1627[27, 27]
1628
1629"""
1630
Tim Petersf6ed0742001-06-27 07:17:57 +00001631__test__ = {"tut": tutorial_tests,
1632 "pep": pep_tests,
1633 "email": email_tests,
1634 "fun": fun_tests,
Tim Petersbe4f0a72001-06-29 02:41:16 +00001635 "syntax": syntax_tests,
Fred Drake56d12662002-08-09 18:37:10 +00001636 "conjoin": conjoin_tests,
1637 "weakref": weakref_tests,
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00001638 "coroutine": coroutine_tests,
Fred Drake56d12662002-08-09 18:37:10 +00001639 }
Tim Peters1def3512001-06-23 20:27:04 +00001640
1641# Magic test name that regrtest.py invokes *after* importing this module.
1642# This worms around a bootstrap problem.
1643# Note that doctest and regrtest both look in sys.argv for a "-v" argument,
1644# so this works as expected in both ways of running regrtest.
Tim Petersa0a62222001-09-09 06:12:01 +00001645def test_main(verbose=None):
Barry Warsaw04f357c2002-07-23 19:04:11 +00001646 from test import test_support, test_generators
Tim Peterscca01832004-08-27 15:29:59 +00001647 test_support.run_doctest(test_generators, verbose)
Tim Peters1def3512001-06-23 20:27:04 +00001648
1649# This part isn't needed for regrtest, but for running the test directly.
1650if __name__ == "__main__":
Tim Petersa0a62222001-09-09 06:12:01 +00001651 test_main(1)