PageRenderTime 64ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/test/test_generators.py

http://github.com/IronLanguages/main
Python | 1907 lines | 1904 code | 2 blank | 1 comment | 0 complexity | 55b3818805509d2b86456c8ff467f2ef MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. tutorial_tests = """
  2. Let's try a simple generator:
  3. >>> def f():
  4. ... yield 1
  5. ... yield 2
  6. >>> for i in f():
  7. ... print i
  8. 1
  9. 2
  10. >>> g = f()
  11. >>> g.next()
  12. 1
  13. >>> g.next()
  14. 2
  15. "Falling off the end" stops the generator:
  16. >>> g.next()
  17. Traceback (most recent call last):
  18. File "<stdin>", line 1, in ?
  19. File "<stdin>", line 2, in g
  20. StopIteration
  21. "return" also stops the generator:
  22. >>> def f():
  23. ... yield 1
  24. ... return
  25. ... yield 2 # never reached
  26. ...
  27. >>> g = f()
  28. >>> g.next()
  29. 1
  30. >>> g.next()
  31. Traceback (most recent call last):
  32. File "<stdin>", line 1, in ?
  33. File "<stdin>", line 3, in f
  34. StopIteration
  35. >>> g.next() # once stopped, can't be resumed
  36. Traceback (most recent call last):
  37. File "<stdin>", line 1, in ?
  38. StopIteration
  39. "raise StopIteration" stops the generator too:
  40. >>> def f():
  41. ... yield 1
  42. ... raise StopIteration
  43. ... yield 2 # never reached
  44. ...
  45. >>> g = f()
  46. >>> g.next()
  47. 1
  48. >>> g.next()
  49. Traceback (most recent call last):
  50. File "<stdin>", line 1, in ?
  51. StopIteration
  52. >>> g.next()
  53. Traceback (most recent call last):
  54. File "<stdin>", line 1, in ?
  55. StopIteration
  56. However, they are not exactly equivalent:
  57. >>> def g1():
  58. ... try:
  59. ... return
  60. ... except:
  61. ... yield 1
  62. ...
  63. >>> list(g1())
  64. []
  65. >>> def g2():
  66. ... try:
  67. ... raise StopIteration
  68. ... except:
  69. ... yield 42
  70. >>> print list(g2())
  71. [42]
  72. This may be surprising at first:
  73. >>> def g3():
  74. ... try:
  75. ... return
  76. ... finally:
  77. ... yield 1
  78. ...
  79. >>> list(g3())
  80. [1]
  81. Let's create an alternate range() function implemented as a generator:
  82. >>> def yrange(n):
  83. ... for i in range(n):
  84. ... yield i
  85. ...
  86. >>> list(yrange(5))
  87. [0, 1, 2, 3, 4]
  88. Generators always return to the most recent caller:
  89. >>> def creator():
  90. ... r = yrange(5)
  91. ... print "creator", r.next()
  92. ... return r
  93. ...
  94. >>> def caller():
  95. ... r = creator()
  96. ... for i in r:
  97. ... print "caller", i
  98. ...
  99. >>> caller()
  100. creator 0
  101. caller 1
  102. caller 2
  103. caller 3
  104. caller 4
  105. Generators can call other generators:
  106. >>> def zrange(n):
  107. ... for i in yrange(n):
  108. ... yield i
  109. ...
  110. >>> list(zrange(5))
  111. [0, 1, 2, 3, 4]
  112. """
  113. # The examples from PEP 255.
  114. pep_tests = """
  115. Specification: Yield
  116. Restriction: A generator cannot be resumed while it is actively
  117. running:
  118. >>> def g():
  119. ... i = me.next()
  120. ... yield i
  121. >>> me = g()
  122. >>> me.next()
  123. Traceback (most recent call last):
  124. ...
  125. File "<string>", line 2, in g
  126. ValueError: generator already executing
  127. Specification: Return
  128. Note that return isn't always equivalent to raising StopIteration: the
  129. difference lies in how enclosing try/except constructs are treated.
  130. For example,
  131. >>> def f1():
  132. ... try:
  133. ... return
  134. ... except:
  135. ... yield 1
  136. >>> print list(f1())
  137. []
  138. because, as in any function, return simply exits, but
  139. >>> def f2():
  140. ... try:
  141. ... raise StopIteration
  142. ... except:
  143. ... yield 42
  144. >>> print list(f2())
  145. [42]
  146. because StopIteration is captured by a bare "except", as is any
  147. exception.
  148. Specification: Generators and Exception Propagation
  149. >>> def f():
  150. ... return 1//0
  151. >>> def g():
  152. ... yield f() # the zero division exception propagates
  153. ... yield 42 # and we'll never get here
  154. >>> k = g()
  155. >>> k.next()
  156. Traceback (most recent call last):
  157. File "<stdin>", line 1, in ?
  158. File "<stdin>", line 2, in g
  159. File "<stdin>", line 2, in f
  160. ZeroDivisionError: integer division or modulo by zero
  161. >>> k.next() # and the generator cannot be resumed
  162. Traceback (most recent call last):
  163. File "<stdin>", line 1, in ?
  164. StopIteration
  165. >>>
  166. Specification: Try/Except/Finally
  167. >>> def f():
  168. ... try:
  169. ... yield 1
  170. ... try:
  171. ... yield 2
  172. ... 1//0
  173. ... yield 3 # never get here
  174. ... except ZeroDivisionError:
  175. ... yield 4
  176. ... yield 5
  177. ... raise
  178. ... except:
  179. ... yield 6
  180. ... yield 7 # the "raise" above stops this
  181. ... except:
  182. ... yield 8
  183. ... yield 9
  184. ... try:
  185. ... x = 12
  186. ... finally:
  187. ... yield 10
  188. ... yield 11
  189. >>> print list(f())
  190. [1, 2, 4, 5, 8, 9, 10, 11]
  191. >>>
  192. Guido's binary tree example.
  193. >>> # A binary tree class.
  194. >>> class Tree:
  195. ...
  196. ... def __init__(self, label, left=None, right=None):
  197. ... self.label = label
  198. ... self.left = left
  199. ... self.right = right
  200. ...
  201. ... def __repr__(self, level=0, indent=" "):
  202. ... s = level*indent + repr(self.label)
  203. ... if self.left:
  204. ... s = s + "\\n" + self.left.__repr__(level+1, indent)
  205. ... if self.right:
  206. ... s = s + "\\n" + self.right.__repr__(level+1, indent)
  207. ... return s
  208. ...
  209. ... def __iter__(self):
  210. ... return inorder(self)
  211. >>> # Create a Tree from a list.
  212. >>> def tree(list):
  213. ... n = len(list)
  214. ... if n == 0:
  215. ... return []
  216. ... i = n // 2
  217. ... return Tree(list[i], tree(list[:i]), tree(list[i+1:]))
  218. >>> # Show it off: create a tree.
  219. >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
  220. >>> # A recursive generator that generates Tree labels in in-order.
  221. >>> def inorder(t):
  222. ... if t:
  223. ... for x in inorder(t.left):
  224. ... yield x
  225. ... yield t.label
  226. ... for x in inorder(t.right):
  227. ... yield x
  228. >>> # Show it off: create a tree.
  229. >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
  230. >>> # Print the nodes of the tree in in-order.
  231. >>> for x in t:
  232. ... print x,
  233. 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
  234. >>> # A non-recursive generator.
  235. >>> def inorder(node):
  236. ... stack = []
  237. ... while node:
  238. ... while node.left:
  239. ... stack.append(node)
  240. ... node = node.left
  241. ... yield node.label
  242. ... while not node.right:
  243. ... try:
  244. ... node = stack.pop()
  245. ... except IndexError:
  246. ... return
  247. ... yield node.label
  248. ... node = node.right
  249. >>> # Exercise the non-recursive generator.
  250. >>> for x in t:
  251. ... print x,
  252. 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
  253. """
  254. # Examples from Iterator-List and Python-Dev and c.l.py.
  255. email_tests = """
  256. The difference between yielding None and returning it.
  257. >>> def g():
  258. ... for i in range(3):
  259. ... yield None
  260. ... yield None
  261. ... return
  262. >>> list(g())
  263. [None, None, None, None]
  264. Ensure that explicitly raising StopIteration acts like any other exception
  265. in try/except, not like a return.
  266. >>> def g():
  267. ... yield 1
  268. ... try:
  269. ... raise StopIteration
  270. ... except:
  271. ... yield 2
  272. ... yield 3
  273. >>> list(g())
  274. [1, 2, 3]
  275. Next one was posted to c.l.py.
  276. >>> def gcomb(x, k):
  277. ... "Generate all combinations of k elements from list x."
  278. ...
  279. ... if k > len(x):
  280. ... return
  281. ... if k == 0:
  282. ... yield []
  283. ... else:
  284. ... first, rest = x[0], x[1:]
  285. ... # A combination does or doesn't contain first.
  286. ... # If it does, the remainder is a k-1 comb of rest.
  287. ... for c in gcomb(rest, k-1):
  288. ... c.insert(0, first)
  289. ... yield c
  290. ... # If it doesn't contain first, it's a k comb of rest.
  291. ... for c in gcomb(rest, k):
  292. ... yield c
  293. >>> seq = range(1, 5)
  294. >>> for k in range(len(seq) + 2):
  295. ... print "%d-combs of %s:" % (k, seq)
  296. ... for c in gcomb(seq, k):
  297. ... print " ", c
  298. 0-combs of [1, 2, 3, 4]:
  299. []
  300. 1-combs of [1, 2, 3, 4]:
  301. [1]
  302. [2]
  303. [3]
  304. [4]
  305. 2-combs of [1, 2, 3, 4]:
  306. [1, 2]
  307. [1, 3]
  308. [1, 4]
  309. [2, 3]
  310. [2, 4]
  311. [3, 4]
  312. 3-combs of [1, 2, 3, 4]:
  313. [1, 2, 3]
  314. [1, 2, 4]
  315. [1, 3, 4]
  316. [2, 3, 4]
  317. 4-combs of [1, 2, 3, 4]:
  318. [1, 2, 3, 4]
  319. 5-combs of [1, 2, 3, 4]:
  320. From the Iterators list, about the types of these things.
  321. >>> def g():
  322. ... yield 1
  323. ...
  324. >>> type(g)
  325. <type 'function'>
  326. >>> i = g()
  327. >>> type(i)
  328. <type 'generator'>
  329. >>> [s for s in dir(i) if not s.startswith('_')]
  330. ['close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw']
  331. >>> from test.test_support import HAVE_DOCSTRINGS
  332. >>> print(i.next.__doc__ if HAVE_DOCSTRINGS else 'x.next() -> the next value, or raise StopIteration')
  333. x.next() -> the next value, or raise StopIteration
  334. >>> iter(i) is i
  335. True
  336. >>> import types
  337. >>> isinstance(i, types.GeneratorType)
  338. True
  339. And more, added later.
  340. >>> i.gi_running
  341. 0
  342. >>> type(i.gi_frame)
  343. <type 'frame'>
  344. >>> i.gi_running = 42
  345. Traceback (most recent call last):
  346. ...
  347. TypeError: readonly attribute
  348. >>> def g():
  349. ... yield me.gi_running
  350. >>> me = g()
  351. >>> me.gi_running
  352. 0
  353. >>> me.next()
  354. 1
  355. >>> me.gi_running
  356. 0
  357. A clever union-find implementation from c.l.py, due to David Eppstein.
  358. Sent: Friday, June 29, 2001 12:16 PM
  359. To: python-list@python.org
  360. Subject: Re: PEP 255: Simple Generators
  361. >>> class disjointSet:
  362. ... def __init__(self, name):
  363. ... self.name = name
  364. ... self.parent = None
  365. ... self.generator = self.generate()
  366. ...
  367. ... def generate(self):
  368. ... while not self.parent:
  369. ... yield self
  370. ... for x in self.parent.generator:
  371. ... yield x
  372. ...
  373. ... def find(self):
  374. ... return self.generator.next()
  375. ...
  376. ... def union(self, parent):
  377. ... if self.parent:
  378. ... raise ValueError("Sorry, I'm not a root!")
  379. ... self.parent = parent
  380. ...
  381. ... def __str__(self):
  382. ... return self.name
  383. >>> names = "ABCDEFGHIJKLM"
  384. >>> sets = [disjointSet(name) for name in names]
  385. >>> roots = sets[:]
  386. >>> import random
  387. >>> gen = random.WichmannHill(42)
  388. >>> while 1:
  389. ... for s in sets:
  390. ... print "%s->%s" % (s, s.find()),
  391. ... print
  392. ... if len(roots) > 1:
  393. ... s1 = gen.choice(roots)
  394. ... roots.remove(s1)
  395. ... s2 = gen.choice(roots)
  396. ... s1.union(s2)
  397. ... print "merged", s1, "into", s2
  398. ... else:
  399. ... break
  400. 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
  401. merged D into G
  402. 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
  403. merged C into F
  404. 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
  405. merged L into A
  406. 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
  407. merged H into E
  408. 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
  409. merged B into E
  410. 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
  411. merged J into G
  412. 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
  413. merged E into G
  414. 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
  415. merged M into G
  416. 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
  417. merged I into K
  418. 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
  419. merged K into A
  420. 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
  421. merged F into A
  422. 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
  423. merged A into G
  424. 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
  425. """
  426. # Emacs turd '
  427. # Fun tests (for sufficiently warped notions of "fun").
  428. fun_tests = """
  429. Build up to a recursive Sieve of Eratosthenes generator.
  430. >>> def firstn(g, n):
  431. ... return [g.next() for i in range(n)]
  432. >>> def intsfrom(i):
  433. ... while 1:
  434. ... yield i
  435. ... i += 1
  436. >>> firstn(intsfrom(5), 7)
  437. [5, 6, 7, 8, 9, 10, 11]
  438. >>> def exclude_multiples(n, ints):
  439. ... for i in ints:
  440. ... if i % n:
  441. ... yield i
  442. >>> firstn(exclude_multiples(3, intsfrom(1)), 6)
  443. [1, 2, 4, 5, 7, 8]
  444. >>> def sieve(ints):
  445. ... prime = ints.next()
  446. ... yield prime
  447. ... not_divisible_by_prime = exclude_multiples(prime, ints)
  448. ... for p in sieve(not_divisible_by_prime):
  449. ... yield p
  450. >>> primes = sieve(intsfrom(2))
  451. >>> firstn(primes, 20)
  452. [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
  453. Another famous problem: generate all integers of the form
  454. 2**i * 3**j * 5**k
  455. in increasing order, where i,j,k >= 0. Trickier than it may look at first!
  456. Try writing it without generators, and correctly, and without generating
  457. 3 internal results for each result output.
  458. >>> def times(n, g):
  459. ... for i in g:
  460. ... yield n * i
  461. >>> firstn(times(10, intsfrom(1)), 10)
  462. [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
  463. >>> def merge(g, h):
  464. ... ng = g.next()
  465. ... nh = h.next()
  466. ... while 1:
  467. ... if ng < nh:
  468. ... yield ng
  469. ... ng = g.next()
  470. ... elif ng > nh:
  471. ... yield nh
  472. ... nh = h.next()
  473. ... else:
  474. ... yield ng
  475. ... ng = g.next()
  476. ... nh = h.next()
  477. The following works, but is doing a whale of a lot of redundant work --
  478. it's not clear how to get the internal uses of m235 to share a single
  479. generator. Note that me_times2 (etc) each need to see every element in the
  480. result sequence. So this is an example where lazy lists are more natural
  481. (you can look at the head of a lazy list any number of times).
  482. >>> def m235():
  483. ... yield 1
  484. ... me_times2 = times(2, m235())
  485. ... me_times3 = times(3, m235())
  486. ... me_times5 = times(5, m235())
  487. ... for i in merge(merge(me_times2,
  488. ... me_times3),
  489. ... me_times5):
  490. ... yield i
  491. Don't print "too many" of these -- the implementation above is extremely
  492. inefficient: each call of m235() leads to 3 recursive calls, and in
  493. turn each of those 3 more, and so on, and so on, until we've descended
  494. enough levels to satisfy the print stmts. Very odd: when I printed 5
  495. lines of results below, this managed to screw up Win98's malloc in "the
  496. usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting
  497. address space, and it *looked* like a very slow leak.
  498. >>> result = m235()
  499. >>> for i in range(3):
  500. ... print firstn(result, 15)
  501. [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
  502. [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
  503. [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
  504. Heh. Here's one way to get a shared list, complete with an excruciating
  505. namespace renaming trick. The *pretty* part is that the times() and merge()
  506. functions can be reused as-is, because they only assume their stream
  507. arguments are iterable -- a LazyList is the same as a generator to times().
  508. >>> class LazyList:
  509. ... def __init__(self, g):
  510. ... self.sofar = []
  511. ... self.fetch = g.next
  512. ...
  513. ... def __getitem__(self, i):
  514. ... sofar, fetch = self.sofar, self.fetch
  515. ... while i >= len(sofar):
  516. ... sofar.append(fetch())
  517. ... return sofar[i]
  518. >>> def m235():
  519. ... yield 1
  520. ... # Gack: m235 below actually refers to a LazyList.
  521. ... me_times2 = times(2, m235)
  522. ... me_times3 = times(3, m235)
  523. ... me_times5 = times(5, m235)
  524. ... for i in merge(merge(me_times2,
  525. ... me_times3),
  526. ... me_times5):
  527. ... yield i
  528. Print as many of these as you like -- *this* implementation is memory-
  529. efficient.
  530. >>> m235 = LazyList(m235())
  531. >>> for i in range(5):
  532. ... print [m235[j] for j in range(15*i, 15*(i+1))]
  533. [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
  534. [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
  535. [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
  536. [200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
  537. [400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
  538. Ye olde Fibonacci generator, LazyList style.
  539. >>> def fibgen(a, b):
  540. ...
  541. ... def sum(g, h):
  542. ... while 1:
  543. ... yield g.next() + h.next()
  544. ...
  545. ... def tail(g):
  546. ... g.next() # throw first away
  547. ... for x in g:
  548. ... yield x
  549. ...
  550. ... yield a
  551. ... yield b
  552. ... for s in sum(iter(fib),
  553. ... tail(iter(fib))):
  554. ... yield s
  555. >>> fib = LazyList(fibgen(1, 2))
  556. >>> firstn(iter(fib), 17)
  557. [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
  558. Running after your tail with itertools.tee (new in version 2.4)
  559. The algorithms "m235" (Hamming) and Fibonacci presented above are both
  560. examples of a whole family of FP (functional programming) algorithms
  561. where a function produces and returns a list while the production algorithm
  562. suppose the list as already produced by recursively calling itself.
  563. For these algorithms to work, they must:
  564. - produce at least a first element without presupposing the existence of
  565. the rest of the list
  566. - produce their elements in a lazy manner
  567. To work efficiently, the beginning of the list must not be recomputed over
  568. and over again. This is ensured in most FP languages as a built-in feature.
  569. In python, we have to explicitly maintain a list of already computed results
  570. and abandon genuine recursivity.
  571. This is what had been attempted above with the LazyList class. One problem
  572. with that class is that it keeps a list of all of the generated results and
  573. therefore continually grows. This partially defeats the goal of the generator
  574. concept, viz. produce the results only as needed instead of producing them
  575. all and thereby wasting memory.
  576. Thanks to itertools.tee, it is now clear "how to get the internal uses of
  577. m235 to share a single generator".
  578. >>> from itertools import tee
  579. >>> def m235():
  580. ... def _m235():
  581. ... yield 1
  582. ... for n in merge(times(2, m2),
  583. ... merge(times(3, m3),
  584. ... times(5, m5))):
  585. ... yield n
  586. ... m1 = _m235()
  587. ... m2, m3, m5, mRes = tee(m1, 4)
  588. ... return mRes
  589. >>> it = m235()
  590. >>> for i in range(5):
  591. ... print firstn(it, 15)
  592. [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
  593. [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
  594. [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
  595. [200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
  596. [400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
  597. The "tee" function does just what we want. It internally keeps a generated
  598. result for as long as it has not been "consumed" from all of the duplicated
  599. iterators, whereupon it is deleted. You can therefore print the hamming
  600. sequence during hours without increasing memory usage, or very little.
  601. The beauty of it is that recursive running-after-their-tail FP algorithms
  602. are quite straightforwardly expressed with this Python idiom.
  603. Ye olde Fibonacci generator, tee style.
  604. >>> def fib():
  605. ...
  606. ... def _isum(g, h):
  607. ... while 1:
  608. ... yield g.next() + h.next()
  609. ...
  610. ... def _fib():
  611. ... yield 1
  612. ... yield 2
  613. ... fibTail.next() # throw first away
  614. ... for res in _isum(fibHead, fibTail):
  615. ... yield res
  616. ...
  617. ... realfib = _fib()
  618. ... fibHead, fibTail, fibRes = tee(realfib, 3)
  619. ... return fibRes
  620. >>> firstn(fib(), 17)
  621. [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
  622. """
  623. # syntax_tests mostly provokes SyntaxErrors. Also fiddling with #if 0
  624. # hackery.
  625. syntax_tests = """
  626. >>> def f():
  627. ... return 22
  628. ... yield 1
  629. Traceback (most recent call last):
  630. ..
  631. SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[0]>, line 3)
  632. >>> def f():
  633. ... yield 1
  634. ... return 22
  635. Traceback (most recent call last):
  636. ..
  637. SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[1]>, line 3)
  638. "return None" is not the same as "return" in a generator:
  639. >>> def f():
  640. ... yield 1
  641. ... return None
  642. Traceback (most recent call last):
  643. ..
  644. SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[2]>, line 3)
  645. These are fine:
  646. >>> def f():
  647. ... yield 1
  648. ... return
  649. >>> def f():
  650. ... try:
  651. ... yield 1
  652. ... finally:
  653. ... pass
  654. >>> def f():
  655. ... try:
  656. ... try:
  657. ... 1//0
  658. ... except ZeroDivisionError:
  659. ... yield 666
  660. ... except:
  661. ... pass
  662. ... finally:
  663. ... pass
  664. >>> def f():
  665. ... try:
  666. ... try:
  667. ... yield 12
  668. ... 1//0
  669. ... except ZeroDivisionError:
  670. ... yield 666
  671. ... except:
  672. ... try:
  673. ... x = 12
  674. ... finally:
  675. ... yield 12
  676. ... except:
  677. ... return
  678. >>> list(f())
  679. [12, 666]
  680. >>> def f():
  681. ... yield
  682. >>> type(f())
  683. <type 'generator'>
  684. >>> def f():
  685. ... if 0:
  686. ... yield
  687. >>> type(f())
  688. <type 'generator'>
  689. >>> def f():
  690. ... if 0:
  691. ... yield 1
  692. >>> type(f())
  693. <type 'generator'>
  694. >>> def f():
  695. ... if "":
  696. ... yield None
  697. >>> type(f())
  698. <type 'generator'>
  699. >>> def f():
  700. ... return
  701. ... try:
  702. ... if x==4:
  703. ... pass
  704. ... elif 0:
  705. ... try:
  706. ... 1//0
  707. ... except SyntaxError:
  708. ... pass
  709. ... else:
  710. ... if 0:
  711. ... while 12:
  712. ... x += 1
  713. ... yield 2 # don't blink
  714. ... f(a, b, c, d, e)
  715. ... else:
  716. ... pass
  717. ... except:
  718. ... x = 1
  719. ... return
  720. >>> type(f())
  721. <type 'generator'>
  722. >>> def f():
  723. ... if 0:
  724. ... def g():
  725. ... yield 1
  726. ...
  727. >>> type(f())
  728. <type 'NoneType'>
  729. >>> def f():
  730. ... if 0:
  731. ... class C:
  732. ... def __init__(self):
  733. ... yield 1
  734. ... def f(self):
  735. ... yield 2
  736. >>> type(f())
  737. <type 'NoneType'>
  738. >>> def f():
  739. ... if 0:
  740. ... return
  741. ... if 0:
  742. ... yield 2
  743. >>> type(f())
  744. <type 'generator'>
  745. >>> def f():
  746. ... if 0:
  747. ... lambda x: x # shouldn't trigger here
  748. ... return # or here
  749. ... def f(i):
  750. ... return 2*i # or here
  751. ... if 0:
  752. ... return 3 # but *this* sucks (line 8)
  753. ... if 0:
  754. ... yield 2 # because it's a generator (line 10)
  755. Traceback (most recent call last):
  756. SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[24]>, line 10)
  757. This one caused a crash (see SF bug 567538):
  758. >>> def f():
  759. ... for i in range(3):
  760. ... try:
  761. ... continue
  762. ... finally:
  763. ... yield i
  764. ...
  765. >>> g = f()
  766. >>> print g.next()
  767. 0
  768. >>> print g.next()
  769. 1
  770. >>> print g.next()
  771. 2
  772. >>> print g.next()
  773. Traceback (most recent call last):
  774. StopIteration
  775. Test the gi_code attribute
  776. >>> def f():
  777. ... yield 5
  778. ...
  779. >>> g = f()
  780. >>> g.gi_code is f.func_code
  781. True
  782. >>> g.next()
  783. 5
  784. >>> g.next()
  785. Traceback (most recent call last):
  786. StopIteration
  787. >>> g.gi_code is f.func_code
  788. True
  789. Test the __name__ attribute and the repr()
  790. >>> def f():
  791. ... yield 5
  792. ...
  793. >>> g = f()
  794. >>> g.__name__
  795. 'f'
  796. >>> repr(g) # doctest: +ELLIPSIS
  797. '<generator object f at ...>'
  798. Lambdas shouldn't have their usual return behavior.
  799. >>> x = lambda: (yield 1)
  800. >>> list(x())
  801. [1]
  802. >>> x = lambda: ((yield 1), (yield 2))
  803. >>> list(x())
  804. [1, 2]
  805. """
  806. # conjoin is a simple backtracking generator, named in honor of Icon's
  807. # "conjunction" control structure. Pass a list of no-argument functions
  808. # that return iterable objects. Easiest to explain by example: assume the
  809. # function list [x, y, z] is passed. Then conjoin acts like:
  810. #
  811. # def g():
  812. # values = [None] * 3
  813. # for values[0] in x():
  814. # for values[1] in y():
  815. # for values[2] in z():
  816. # yield values
  817. #
  818. # So some 3-lists of values *may* be generated, each time we successfully
  819. # get into the innermost loop. If an iterator fails (is exhausted) before
  820. # then, it "backtracks" to get the next value from the nearest enclosing
  821. # iterator (the one "to the left"), and starts all over again at the next
  822. # slot (pumps a fresh iterator). Of course this is most useful when the
  823. # iterators have side-effects, so that which values *can* be generated at
  824. # each slot depend on the values iterated at previous slots.
  825. def simple_conjoin(gs):
  826. values = [None] * len(gs)
  827. def gen(i):
  828. if i >= len(gs):
  829. yield values
  830. else:
  831. for values[i] in gs[i]():
  832. for x in gen(i+1):
  833. yield x
  834. for x in gen(0):
  835. yield x
  836. # That works fine, but recursing a level and checking i against len(gs) for
  837. # each item produced is inefficient. By doing manual loop unrolling across
  838. # generator boundaries, it's possible to eliminate most of that overhead.
  839. # This isn't worth the bother *in general* for generators, but conjoin() is
  840. # a core building block for some CPU-intensive generator applications.
  841. def conjoin(gs):
  842. n = len(gs)
  843. values = [None] * n
  844. # Do one loop nest at time recursively, until the # of loop nests
  845. # remaining is divisible by 3.
  846. def gen(i):
  847. if i >= n:
  848. yield values
  849. elif (n-i) % 3:
  850. ip1 = i+1
  851. for values[i] in gs[i]():
  852. for x in gen(ip1):
  853. yield x
  854. else:
  855. for x in _gen3(i):
  856. yield x
  857. # Do three loop nests at a time, recursing only if at least three more
  858. # remain. Don't call directly: this is an internal optimization for
  859. # gen's use.
  860. def _gen3(i):
  861. assert i < n and (n-i) % 3 == 0
  862. ip1, ip2, ip3 = i+1, i+2, i+3
  863. g, g1, g2 = gs[i : ip3]
  864. if ip3 >= n:
  865. # These are the last three, so we can yield values directly.
  866. for values[i] in g():
  867. for values[ip1] in g1():
  868. for values[ip2] in g2():
  869. yield values
  870. else:
  871. # At least 6 loop nests remain; peel off 3 and recurse for the
  872. # rest.
  873. for values[i] in g():
  874. for values[ip1] in g1():
  875. for values[ip2] in g2():
  876. for x in _gen3(ip3):
  877. yield x
  878. for x in gen(0):
  879. yield x
  880. # And one more approach: For backtracking apps like the Knight's Tour
  881. # solver below, the number of backtracking levels can be enormous (one
  882. # level per square, for the Knight's Tour, so that e.g. a 100x100 board
  883. # needs 10,000 levels). In such cases Python is likely to run out of
  884. # stack space due to recursion. So here's a recursion-free version of
  885. # conjoin too.
  886. # NOTE WELL: This allows large problems to be solved with only trivial
  887. # demands on stack space. Without explicitly resumable generators, this is
  888. # much harder to achieve. OTOH, this is much slower (up to a factor of 2)
  889. # than the fancy unrolled recursive conjoin.
  890. def flat_conjoin(gs): # rename to conjoin to run tests with this instead
  891. n = len(gs)
  892. values = [None] * n
  893. iters = [None] * n
  894. _StopIteration = StopIteration # make local because caught a *lot*
  895. i = 0
  896. while 1:
  897. # Descend.
  898. try:
  899. while i < n:
  900. it = iters[i] = gs[i]().next
  901. values[i] = it()
  902. i += 1
  903. except _StopIteration:
  904. pass
  905. else:
  906. assert i == n
  907. yield values
  908. # Backtrack until an older iterator can be resumed.
  909. i -= 1
  910. while i >= 0:
  911. try:
  912. values[i] = iters[i]()
  913. # Success! Start fresh at next level.
  914. i += 1
  915. break
  916. except _StopIteration:
  917. # Continue backtracking.
  918. i -= 1
  919. else:
  920. assert i < 0
  921. break
  922. # A conjoin-based N-Queens solver.
  923. class Queens:
  924. def __init__(self, n):
  925. self.n = n
  926. rangen = range(n)
  927. # Assign a unique int to each column and diagonal.
  928. # columns: n of those, range(n).
  929. # NW-SE diagonals: 2n-1 of these, i-j unique and invariant along
  930. # each, smallest i-j is 0-(n-1) = 1-n, so add n-1 to shift to 0-
  931. # based.
  932. # NE-SW diagonals: 2n-1 of these, i+j unique and invariant along
  933. # each, smallest i+j is 0, largest is 2n-2.
  934. # For each square, compute a bit vector of the columns and
  935. # diagonals it covers, and for each row compute a function that
  936. # generates the possibilities for the columns in that row.
  937. self.rowgenerators = []
  938. for i in rangen:
  939. rowuses = [(1L << j) | # column ordinal
  940. (1L << (n + i-j + n-1)) | # NW-SE ordinal
  941. (1L << (n + 2*n-1 + i+j)) # NE-SW ordinal
  942. for j in rangen]
  943. def rowgen(rowuses=rowuses):
  944. for j in rangen:
  945. uses = rowuses[j]
  946. if uses & self.used == 0:
  947. self.used |= uses
  948. yield j
  949. self.used &= ~uses
  950. self.rowgenerators.append(rowgen)
  951. # Generate solutions.
  952. def solve(self):
  953. self.used = 0
  954. for row2col in conjoin(self.rowgenerators):
  955. yield row2col
  956. def printsolution(self, row2col):
  957. n = self.n
  958. assert n == len(row2col)
  959. sep = "+" + "-+" * n
  960. print sep
  961. for i in range(n):
  962. squares = [" " for j in range(n)]
  963. squares[row2col[i]] = "Q"
  964. print "|" + "|".join(squares) + "|"
  965. print sep
  966. # A conjoin-based Knight's Tour solver. This is pretty sophisticated
  967. # (e.g., when used with flat_conjoin above, and passing hard=1 to the
  968. # constructor, a 200x200 Knight's Tour was found quickly -- note that we're
  969. # creating 10s of thousands of generators then!), and is lengthy.
  970. class Knights:
  971. def __init__(self, m, n, hard=0):
  972. self.m, self.n = m, n
  973. # solve() will set up succs[i] to be a list of square #i's
  974. # successors.
  975. succs = self.succs = []
  976. # Remove i0 from each of its successor's successor lists, i.e.
  977. # successors can't go back to i0 again. Return 0 if we can
  978. # detect this makes a solution impossible, else return 1.
  979. def remove_from_successors(i0, len=len):
  980. # If we remove all exits from a free square, we're dead:
  981. # even if we move to it next, we can't leave it again.
  982. # If we create a square with one exit, we must visit it next;
  983. # else somebody else will have to visit it, and since there's
  984. # only one adjacent, there won't be a way to leave it again.
  985. # Finelly, if we create more than one free square with a
  986. # single exit, we can only move to one of them next, leaving
  987. # the other one a dead end.
  988. ne0 = ne1 = 0
  989. for i in succs[i0]:
  990. s = succs[i]
  991. s.remove(i0)
  992. e = len(s)
  993. if e == 0:
  994. ne0 += 1
  995. elif e == 1:
  996. ne1 += 1
  997. return ne0 == 0 and ne1 < 2
  998. # Put i0 back in each of its successor's successor lists.
  999. def add_to_successors(i0):
  1000. for i in succs[i0]:
  1001. succs[i].append(i0)
  1002. # Generate the first move.
  1003. def first():
  1004. if m < 1 or n < 1:
  1005. return
  1006. # Since we're looking for a cycle, it doesn't matter where we
  1007. # start. Starting in a corner makes the 2nd move easy.
  1008. corner = self.coords2index(0, 0)
  1009. remove_from_successors(corner)
  1010. self.lastij = corner
  1011. yield corner
  1012. add_to_successors(corner)
  1013. # Generate the second moves.
  1014. def second():
  1015. corner = self.coords2index(0, 0)
  1016. assert self.lastij == corner # i.e., we started in the corner
  1017. if m < 3 or n < 3:
  1018. return
  1019. assert len(succs[corner]) == 2
  1020. assert self.coords2index(1, 2) in succs[corner]
  1021. assert self.coords2index(2, 1) in succs[corner]
  1022. # Only two choices. Whichever we pick, the other must be the
  1023. # square picked on move m*n, as it's the only way to get back
  1024. # to (0, 0). Save its index in self.final so that moves before
  1025. # the last know it must be kept free.
  1026. for i, j in (1, 2), (2, 1):
  1027. this = self.coords2index(i, j)
  1028. final = self.coords2index(3-i, 3-j)
  1029. self.final = final
  1030. remove_from_successors(this)
  1031. succs[final].append(corner)
  1032. self.lastij = this
  1033. yield this
  1034. succs[final].remove(corner)
  1035. add_to_successors(this)
  1036. # Generate moves 3 thru m*n-1.
  1037. def advance(len=len):
  1038. # If some successor has only one exit, must take it.
  1039. # Else favor successors with fewer exits.
  1040. candidates = []
  1041. for i in succs[self.lastij]:
  1042. e = len(succs[i])
  1043. assert e > 0, "else remove_from_successors() pruning flawed"
  1044. if e == 1:
  1045. candidates = [(e, i)]
  1046. break
  1047. candidates.append((e, i))
  1048. else:
  1049. candidates.sort()
  1050. for e, i in candidates:
  1051. if i != self.final:
  1052. if remove_from_successors(i):
  1053. self.lastij = i
  1054. yield i
  1055. add_to_successors(i)
  1056. # Generate moves 3 thru m*n-1. Alternative version using a
  1057. # stronger (but more expensive) heuristic to order successors.
  1058. # Since the # of backtracking levels is m*n, a poor move early on
  1059. # can take eons to undo. Smallest square board for which this
  1060. # matters a lot is 52x52.
  1061. def advance_hard(vmid=(m-1)/2.0, hmid=(n-1)/2.0, len=len):
  1062. # If some successor has only one exit, must take it.
  1063. # Else favor successors with fewer exits.
  1064. # Break ties via max distance from board centerpoint (favor
  1065. # corners and edges whenever possible).
  1066. candidates = []
  1067. for i in succs[self.lastij]:
  1068. e = len(succs[i])
  1069. assert e > 0, "else remove_from_successors() pruning flawed"
  1070. if e == 1:
  1071. candidates = [(e, 0, i)]
  1072. break
  1073. i1, j1 = self.index2coords(i)
  1074. d = (i1 - vmid)**2 + (j1 - hmid)**2
  1075. candidates.append((e, -d, i))
  1076. else:
  1077. candidates.sort()
  1078. for e, d, i in candidates:
  1079. if i != self.final:
  1080. if remove_from_successors(i):
  1081. self.lastij = i
  1082. yield i
  1083. add_to_successors(i)
  1084. # Generate the last move.
  1085. def last():
  1086. assert self.final in succs[self.lastij]
  1087. yield self.final
  1088. if m*n < 4:
  1089. self.squaregenerators = [first]
  1090. else:
  1091. self.squaregenerators = [first, second] + \
  1092. [hard and advance_hard or advance] * (m*n - 3) + \
  1093. [last]
  1094. def coords2index(self, i, j):
  1095. assert 0 <= i < self.m
  1096. assert 0 <= j < self.n
  1097. return i * self.n + j
  1098. def index2coords(self, index):
  1099. assert 0 <= index < self.m * self.n
  1100. return divmod(index, self.n)
  1101. def _init_board(self):
  1102. succs = self.succs
  1103. del succs[:]
  1104. m, n = self.m, self.n
  1105. c2i = self.coords2index
  1106. offsets = [( 1, 2), ( 2, 1), ( 2, -1), ( 1, -2),
  1107. (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
  1108. rangen = range(n)
  1109. for i in range(m):
  1110. for j in rangen:
  1111. s = [c2i(i+io, j+jo) for io, jo in offsets
  1112. if 0 <= i+io < m and
  1113. 0 <= j+jo < n]
  1114. succs.append(s)
  1115. # Generate solutions.
  1116. def solve(self):
  1117. self._init_board()
  1118. for x in conjoin(self.squaregenerators):
  1119. yield x
  1120. def printsolution(self, x):
  1121. m, n = self.m, self.n
  1122. assert len(x) == m*n
  1123. w = len(str(m*n))
  1124. format = "%" + str(w) + "d"
  1125. squares = [[None] * n for i in range(m)]
  1126. k = 1
  1127. for i in x:
  1128. i1, j1 = self.index2coords(i)
  1129. squares[i1][j1] = format % k
  1130. k += 1
  1131. sep = "+" + ("-" * w + "+") * n
  1132. print sep
  1133. for i in range(m):
  1134. row = squares[i]
  1135. print "|" + "|".join(row) + "|"
  1136. print sep
  1137. conjoin_tests = """
  1138. Generate the 3-bit binary numbers in order. This illustrates dumbest-
  1139. possible use of conjoin, just to generate the full cross-product.
  1140. >>> for c in conjoin([lambda: iter((0, 1))] * 3):
  1141. ... print c
  1142. [0, 0, 0]
  1143. [0, 0, 1]
  1144. [0, 1, 0]
  1145. [0, 1, 1]
  1146. [1, 0, 0]
  1147. [1, 0, 1]
  1148. [1, 1, 0]
  1149. [1, 1, 1]
  1150. For efficiency in typical backtracking apps, conjoin() yields the same list
  1151. object each time. So if you want to save away a full account of its
  1152. generated sequence, you need to copy its results.
  1153. >>> def gencopy(iterator):
  1154. ... for x in iterator:
  1155. ... yield x[:]
  1156. >>> for n in range(10):
  1157. ... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n)))
  1158. ... print n, len(all), all[0] == [0] * n, all[-1] == [1] * n
  1159. 0 1 True True
  1160. 1 2 True True
  1161. 2 4 True True
  1162. 3 8 True True
  1163. 4 16 True True
  1164. 5 32 True True
  1165. 6 64 True True
  1166. 7 128 True True
  1167. 8 256 True True
  1168. 9 512 True True
  1169. And run an 8-queens solver.
  1170. >>> q = Queens(8)
  1171. >>> LIMIT = 2
  1172. >>> count = 0
  1173. >>> for row2col in q.solve():
  1174. ... count += 1
  1175. ... if count <= LIMIT:
  1176. ... print "Solution", count
  1177. ... q.printsolution(row2col)
  1178. Solution 1
  1179. +-+-+-+-+-+-+-+-+
  1180. |Q| | | | | | | |
  1181. +-+-+-+-+-+-+-+-+
  1182. | | | | |Q| | | |
  1183. +-+-+-+-+-+-+-+-+
  1184. | | | | | | | |Q|
  1185. +-+-+-+-+-+-+-+-+
  1186. | | | | | |Q| | |
  1187. +-+-+-+-+-+-+-+-+
  1188. | | |Q| | | | | |
  1189. +-+-+-+-+-+-+-+-+
  1190. | | | | | | |Q| |
  1191. +-+-+-+-+-+-+-+-+
  1192. | |Q| | | | | | |
  1193. +-+-+-+-+-+-+-+-+
  1194. | | | |Q| | | | |
  1195. +-+-+-+-+-+-+-+-+
  1196. Solution 2
  1197. +-+-+-+-+-+-+-+-+
  1198. |Q| | | | | | | |
  1199. +-+-+-+-+-+-+-+-+
  1200. | | | | | |Q| | |
  1201. +-+-+-+-+-+-+-+-+
  1202. | | | | | | | |Q|
  1203. +-+-+-+-+-+-+-+-+
  1204. | | |Q| | | | | |
  1205. +-+-+-+-+-+-+-+-+
  1206. | | | | | | |Q| |
  1207. +-+-+-+-+-+-+-+-+
  1208. | | | |Q| | | | |
  1209. +-+-+-+-+-+-+-+-+
  1210. | |Q| | | | | | |
  1211. +-+-+-+-+-+-+-+-+
  1212. | | | | |Q| | | |
  1213. +-+-+-+-+-+-+-+-+
  1214. >>> print count, "solutions in all."
  1215. 92 solutions in all.
  1216. And run a Knight's Tour on a 10x10 board. Note that there are about
  1217. 20,000 solutions even on a 6x6 board, so don't dare run this to exhaustion.
  1218. >>> k = Knights(10, 10)
  1219. >>> LIMIT = 2
  1220. >>> count = 0
  1221. >>> for x in k.solve():
  1222. ... count += 1
  1223. ... if count <= LIMIT:
  1224. ... print "Solution", count
  1225. ... k.printsolution(x)
  1226. ... else:
  1227. ... break
  1228. Solution 1
  1229. +---+---+---+---+---+---+---+---+---+---+
  1230. | 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
  1231. +---+---+---+---+---+---+---+---+---+---+
  1232. | 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
  1233. +---+---+---+---+---+---+---+---+---+---+
  1234. | 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
  1235. +---+---+---+---+---+---+---+---+---+---+
  1236. | 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
  1237. +---+---+---+---+---+---+---+---+---+---+
  1238. | 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
  1239. +---+---+---+---+---+---+---+---+---+---+
  1240. | 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
  1241. +---+---+---+---+---+---+---+---+---+---+
  1242. | 87| 98| 91| 80| 77| 84| 53| 46| 65| 44|
  1243. +---+---+---+---+---+---+---+---+---+---+
  1244. | 90| 23| 88| 95| 70| 79| 68| 83| 14| 17|
  1245. +---+---+---+---+---+---+---+---+---+---+
  1246. | 97| 92| 21| 78| 81| 94| 19| 16| 45| 66|
  1247. +---+---+---+---+---+---+---+---+---+---+
  1248. | 22| 89| 96| 93| 20| 69| 82| 67| 18| 15|
  1249. +---+---+---+---+---+---+---+---+---+---+
  1250. Solution 2
  1251. +---+---+---+---+---+---+---+---+---+---+
  1252. | 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
  1253. +---+---+---+---+---+---+---+---+---+---+
  1254. | 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
  1255. +---+---+---+---+---+---+---+---+---+---+
  1256. | 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
  1257. +---+---+---+---+---+---+---+---+---+---+
  1258. | 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
  1259. +---+---+---+---+---+---+---+---+---+---+
  1260. | 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
  1261. +---+---+---+---+---+---+---+---+---+---+
  1262. | 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
  1263. +---+---+---+---+---+---+---+---+---+---+
  1264. | 87| 98| 89| 80| 77| 84| 53| 46| 65| 44|
  1265. +---+---+---+---+---+---+---+---+---+---+
  1266. | 90| 23| 92| 95| 70| 79| 68| 83| 14| 17|
  1267. +---+---+---+---+---+---+---+---+---+---+
  1268. | 97| 88| 21| 78| 81| 94| 19| 16| 45| 66|
  1269. +---+---+---+---+---+---+---+---+---+---+
  1270. | 22| 91| 96| 93| 20| 69| 82| 67| 18| 15|
  1271. +---+---+---+---+---+---+---+---+---+---+
  1272. """
  1273. weakref_tests = """\
  1274. Generators are weakly referencable:
  1275. >>> import weakref
  1276. >>> def gen():
  1277. ... yield 'foo!'
  1278. ...
  1279. >>> wr = weakref.ref(gen)
  1280. >>> wr() is gen
  1281. True
  1282. >>> p = weakref.proxy(gen)
  1283. Generator-iterators are weakly referencable as well:
  1284. >>> gi = gen()
  1285. >>> wr = weakref.ref(gi)
  1286. >>> wr() is gi
  1287. True
  1288. >>> p = weakref.proxy(gi)
  1289. >>> list(p)
  1290. ['foo!']
  1291. """
  1292. coroutine_tests = """\
  1293. Sending a value into a started generator:
  1294. >>> def f():
  1295. ... print (yield 1)
  1296. ... yield 2
  1297. >>> g = f()
  1298. >>> g.next()
  1299. 1
  1300. >>> g.send(42)
  1301. 42
  1302. 2
  1303. Sending a value into a new generator produces a TypeError:
  1304. >>> f().send("foo")
  1305. Traceback (most recent call last):
  1306. ...
  1307. TypeError: can't send non-None value to a just-started generator
  1308. Yield by itself yields None:
  1309. >>> def f(): yield
  1310. >>> list(f())
  1311. [None]
  1312. An obscene abuse of a yield expression within a generator expression:
  1313. >>> list((yield 21) for i in range(4))
  1314. [21, None, 21, None, 21, None, 21, None]
  1315. And a more sane, but still weird usage:
  1316. >>> def f(): list(i for i in [(yield 26)])
  1317. >>> type(f())
  1318. <type 'generator'>
  1319. A yield expression with augmented assignment.
  1320. >>> def coroutine(seq):
  1321. ... count = 0
  1322. ... while count < 200:
  1323. ... count += yield
  1324. ... seq.append(count)
  1325. >>> seq = []
  1326. >>> c = coroutine(seq)
  1327. >>> c.next()
  1328. >>> print seq
  1329. []
  1330. >>> c.send(10)
  1331. >>> print seq
  1332. [10]
  1333. >>> c.send(10)
  1334. >>> print seq
  1335. [10, 20]
  1336. >>> c.send(10)
  1337. >>> print seq
  1338. [10, 20, 30]
  1339. Check some syntax errors for yield expressions:
  1340. >>> f=lambda: (yield 1),(yield 2)
  1341. Traceback (most recent call last):
  1342. ...
  1343. File "<doctest test.test_generators.__test__.coroutine[21]>", line 1
  1344. SyntaxError: 'yield' outside function
  1345. >>> def f(): return lambda x=(yield): 1
  1346. Traceback (most recent call last):
  1347. ...
  1348. SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.coroutine[22]>, line 1)
  1349. >>> def f(): x = yield = y
  1350. Traceback (most recent call last):
  1351. ...
  1352. File "<doctest test.test_generators.__test__.coroutine[23]>", line 1
  1353. SyntaxError: assignment to yield expression not possible
  1354. >>> def f(): (yield bar) = y
  1355. Traceback (most recent call last):
  1356. ...
  1357. File "<doctest test.test_generators.__test__.coroutine[24]>", line 1
  1358. SyntaxError: can't assign to yield expression
  1359. >>> def f(): (yield bar) += y
  1360. Traceback (most recent call last):
  1361. ...
  1362. File "<doctest test.test_generators.__test__.coroutine[25]>", line 1
  1363. SyntaxError: can't assign to yield expression
  1364. Now check some throw() conditions:
  1365. >>> def f():
  1366. ... while True:
  1367. ... try:
  1368. ... print (yield)
  1369. ... except ValueError,v:
  1370. ... print "caught ValueError (%s)" % (v),
  1371. >>> import sys
  1372. >>> g = f()
  1373. >>> g.next()
  1374. >>> g.throw(ValueError) # type only
  1375. caught ValueError ()
  1376. >>> g.throw(ValueError("xyz")) # value only
  1377. caught ValueError (xyz)
  1378. >>> g.throw(ValueError, ValueError(1)) # value+matching type
  1379. caught ValueError (1)
  1380. >>> g.throw(ValueError, TypeError(1)) # mismatched type, rewrapped
  1381. caught ValueError (1)
  1382. >>> g.throw(ValueError, ValueError(1), None) # explicit None traceback
  1383. caught ValueError (1)
  1384. >>> g.throw(ValueError(1), "foo") # bad args
  1385. Traceback (most recent call last):
  1386. ...
  1387. TypeError: instance exception may not have a separate value
  1388. >>> g.throw(ValueError, "foo", 23) # bad args
  1389. Traceback (most recent call last):
  1390. ...
  1391. TypeError: throw() third argument must be a traceback object
  1392. >>> def throw(g,exc):
  1393. ... try:
  1394. ... raise exc
  1395. ... except:
  1396. ... g.throw(*sys.exc_info())
  1397. >>> throw(g,ValueError) # do it with traceback included
  1398. caught ValueError ()
  1399. >>> g.send(1)
  1400. 1
  1401. >>> throw(g,TypeError) # terminate the generator
  1402. Traceback (most recent call last):
  1403. ...
  1404. TypeError
  1405. >>> print g.gi_frame
  1406. None
  1407. >>> g.send(2)
  1408. Traceback (most recent call last):
  1409. ...
  1410. StopIteration
  1411. >>> g.throw(ValueError,6) # throw on closed generator
  1412. Traceback (most recent call last):
  1413. ...
  1414. ValueError: 6
  1415. >>> f().throw(ValueError,7) # throw on just-opened generator
  1416. Traceback (most recent call last):
  1417. ...
  1418. ValueError: 7
  1419. >>> f().throw("abc") # throw on just-opened generator
  1420. Traceback (most recent call last):
  1421. ...
  1422. TypeError: exceptions must be classes, or instances, not str
  1423. Now let's try closing a generator:
  1424. >>> def f():
  1425. ... try: yield
  1426. ... except GeneratorExit:
  1427. ... print "exiting"
  1428. >>> g = f()
  1429. >>> g.next()
  1430. >>> g.close()
  1431. exiting
  1432. >>> g.close() # should be no-op now
  1433. >>> f().close() # close on just-opened generator should be fine
  1434. >>> def f(): yield # an even simpler generator
  1435. >>> f().close() # close before opening
  1436. >>> g = f()
  1437. >>> g.next()
  1438. >>> g.close() # close normally
  1439. And finalization:
  1440. >>> def f():
  1441. ... try: yield
  1442. ... finally:
  1443. ... print "exiting"
  1444. >>> g = f()
  1445. >>> g.next()
  1446. >>> del g
  1447. exiting
  1448. >>> class context(object):
  1449. ... def __enter__(self): pass
  1450. ... def __exit__(self, *args): print 'exiting'
  1451. >>> def f():
  1452. ... with context():
  1453. ... yield
  1454. >>> g = f()
  1455. >>> g.next()
  1456. >>> del g
  1457. exiting
  1458. GeneratorExit is not caught by except Exception:
  1459. >>> def f():
  1460. ... try: yield
  1461. ... except Exception: print 'except'
  1462. ... finally: print 'finally'
  1463. >>> g = f()
  1464. >>> g.next()
  1465. >>> del g
  1466. finally
  1467. Now let's try some ill-behaved generators:
  1468. >>> def f():
  1469. ... try: yield
  1470. ... except GeneratorExit:
  1471. ... yield "foo!"
  1472. >>> g = f()
  1473. >>> g.next()
  1474. >>> g.close()
  1475. Traceback (most recent call last):
  1476. ...
  1477. RuntimeError: generator ignored GeneratorExit
  1478. >>> g.close()
  1479. Our ill-behaved code should be invoked during GC:
  1480. >>> import sys, StringIO
  1481. >>> old, sys.stderr = sys.stderr, StringIO.StringIO()
  1482. >>> g = f()
  1483. >>> g.next()
  1484. >>> del g
  1485. >>> sys.stderr.getvalue().startswith(
  1486. ... "Exception RuntimeError: 'generator ignored GeneratorExit' in "
  1487. ... )
  1488. True
  1489. >>> sys.stderr = old
  1490. And errors thrown during closing should propagate:
  1491. >>> def f():
  1492. ... try: yield
  1493. ... except GeneratorExit:
  1494. ... raise TypeError("fie!")
  1495. >>> g = f()
  1496. >>> g.next()
  1497. >>> g.close()
  1498. Traceback (most recent call last):
  1499. ...
  1500. TypeError: fie!
  1501. Ensure that various yield expression constructs make their
  1502. enclosing function a generator:
  1503. >>> def f(): x += yield
  1504. >>> type(f())
  1505. <type 'generator'>
  1506. >>> def f(): x = yield
  1507. >>> type(f())
  1508. <type 'generator'>
  1509. >>> def f(): lambda x=(yield): 1
  1510. >>> type(f())
  1511. <type 'generator'>
  1512. >>> def f(): x=(i for i in (yield) if (yield))
  1513. >>> type(f())
  1514. <type 'generator'>
  1515. >>> def f(d): d[(yield "a")] = d[(yield "b")] = 27
  1516. >>> data = [1,2]
  1517. >>> g = f(data)
  1518. >>> type(g)
  1519. <type 'generator'>
  1520. >>> g.send(None)
  1521. 'a'
  1522. >>> data
  1523. [1, 2]
  1524. >>> g.send(0)
  1525. 'b'
  1526. >>> data
  1527. [27, 2]
  1528. >>> try: g.send(1)
  1529. ... except StopIteration: pass
  1530. >>> data
  1531. [27, 27]
  1532. """
  1533. refleaks_tests = """
  1534. Prior to adding cycle-GC support to itertools.tee, this code would leak
  1535. references. We add it to the standard suite so the routine refleak-tests
  1536. would trigger if it starts being uncleanable again.
  1537. >>> import itertools
  1538. >>> def leak():
  1539. ... class gen:
  1540. ... def __iter__(self):
  1541. ... return self
  1542. ... def next(self):
  1543. ... return self.item
  1544. ... g = gen()
  1545. ... head, tail = itertools.tee(g)
  1546. ... g.item = head
  1547. ... return head
  1548. >>> it = leak()
  1549. Make sure to also test the involvement of the tee-internal teedataobject,
  1550. which stores returned items.
  1551. >>> item = it.next()
  1552. This test leaked at one point due to generator finalization/destruction.
  1553. It was copied from Lib/test/leakers/test_generator_cycle.py before the file
  1554. was removed.
  1555. >>> def leak():
  1556. ... def gen():
  1557. ... while True:
  1558. ... yield g
  1559. ... g = gen()
  1560. >>> leak()
  1561. This test isn't really generator related, but rather exception-in-cleanup
  1562. related. The coroutine tests (above) just happen to cause an exception in
  1563. the generator's __del__ (tp_del) method. We can also test for this
  1564. explicitly, without generators. We do have to redirect stderr to avoid
  1565. printing warnings and to doublecheck that we actually tested what we wanted
  1566. to test.
  1567. >>> import sys, StringIO
  1568. >>> old = sys.stderr
  1569. >>> try:
  1570. ... sys.stderr = StringIO.StringIO()
  1571. ... class Leaker:
  1572. ... def __del__(self):
  1573. ... raise RuntimeError
  1574. ...
  1575. ... l = Leaker()
  1576. ... del l
  1577. ... err = sys.stderr.getvalue().strip()
  1578. ... err.startswith(
  1579. ... "Exception RuntimeError: RuntimeError() in <"
  1580. ... )
  1581. ... err.endswith("> ignored")
  1582. ... len(err.splitlines())
  1583. ... finally:
  1584. ... sys.stderr = old
  1585. True
  1586. True
  1587. 1
  1588. These refleak tests should perhaps be in a testfile of their own,
  1589. test_generators just happened to be the test that drew these out.
  1590. """
  1591. __test__ = {"tut": tutorial_tests,
  1592. "pep": pep_tests,
  1593. "email":

Large files files are truncated, but you can click here to view the full file