Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b9b281b

Browse files
committed
Add some simple examples to the PEP 380 section of What's New
1 parent 98e2070 commit b9b281b

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Doc/whatsnew/3.3.rst

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,9 +262,56 @@ part of its operations to another generator. This allows a section of code
262262
containing 'yield' to be factored out and placed in another generator.
263263
Additionally, the subgenerator is allowed to return with a value, and the
264264
value is made available to the delegating generator.
265+
265266
While designed primarily for use in delegating to a subgenerator, the ``yield
266267
from`` expression actually allows delegation to arbitrary subiterators.
267268

269+
For simple iterators, ``yield from iterable`` is essentially just a shortened
270+
form of ``for item in iterable: yield item``::
271+
272+
>>> def g(x):
273+
... yield from range(x, 0, -1)
274+
... yield from range(x)
275+
...
276+
>>> list(g(5))
277+
[5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
278+
279+
However, unlike an ordinary loop, ``yield from`` allows subgenerators to
280+
receive sent and thrown values directly from the calling scope, and
281+
return a final value to the outer generator::
282+
283+
>>> def accumulate(start=0):
284+
... tally = start
285+
... while 1:
286+
... next = yield
287+
... if next is None:
288+
... return tally
289+
... tally += next
290+
...
291+
>>> def gather_tallies(tallies, start=0):
292+
... while 1:
293+
... tally = yield from accumulate()
294+
... tallies.append(tally)
295+
...
296+
>>> tallies = []
297+
>>> acc = gather_tallies(tallies)
298+
>>> next(acc) # Ensure the accumulator is ready to accept values
299+
>>> for i in range(10):
300+
... acc.send(i)
301+
...
302+
>>> acc.send(None) # Finish the first tally
303+
>>> for i in range(5):
304+
... acc.send(i)
305+
...
306+
>>> acc.send(None) # Finish the second tally
307+
>>> tallies
308+
[45, 10]
309+
310+
The main principle driving this change is to allow even generators that are
311+
designed to be used with the ``send`` and ``throw`` methods to be split into
312+
multiple subgenerators as easily as a single large function can be split into
313+
multiple subfunctions.
314+
268315
(Implementation by Greg Ewing, integrated into 3.3 by Renaud Blanch, Ryan
269316
Kelly and Nick Coghlan, documentation by Zbigniew Jędrzejewski-Szmek and
270317
Nick Coghlan)

0 commit comments

Comments
 (0)