For most applications, it yield fromsimply prints everything left and back in order:
def iterable1():
yield 1
yield 2
def iterable2():
yield from iterable1()
yield 3
assert list(iterable2) == [1, 2, 3]
For 90% of users who see this post, I assume that for them this will be enough explanation. yield fromjust delegates iterability on the right side.
Coroutines
, , . , . , , :
def coroutine():
x = yield None
yield 'You sent: %s' % x
c = coroutine()
next(c)
print(c.send('Hello world'))
: , ( ). contextlib.contextmanager. . , , API- google app-engine ndb API datastore .
, send , ... ? , python2.x, :
def python2_generator_wapper():
for item in some_wrapped_generator():
yield item
, :
def python2_coroutine_wrapper():
"""This doesn't work. Somebody smarter than me needs to fix it. . .
Pain. Misery. Death lurks here :-("""
g = some_wrapped_generator()
for item in g:
try:
val = yield item
except Exception as forward_exception:
g.throw(forward_exception)
else:
if val is not None:
g.send(val)
yield from:
def coroutine_wrapper():
yield from coroutine()
yield from (!) .
, PEP . OP, , . python2.x :
def iterable():
yield 'foo'
return 'done'
a SyntaxError. yield . , - (. ). , (, ?), . , StopIteration ( ), StopIteration . , :
raise StopIteration('done')
- , .