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

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

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

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