[Edu-sig] pep380: yield from
kirby urner
kirby.urner at gmail.com
Mon Jan 4 15:29:55 EST 2016
I working through Luciano's Fluent Python, which I really appreciate
reading in Safari On-Line as so many of the links are live and relevant.
Luciano packs his 'For Further Reading' with links directly in Google
groups, where we can see Guido studying Twisted so to better communicate
his alternative vision in asyncio (formerly tulip).
Here's a tiny test module I'm using, based on Gregory Ewing's PEP 380.
https://www.python.org/dev/peps/pep-0380/
from itertools import takewhile
def fibo(a,b):
"Fibonacci Numbers with any seed"
while True:
yield a
a, b = a + b, a
def pep380(EXPR):
_i = iter(EXPR)
try:
_y = next(_i)
except StopIteration as _e:
_r = _e.value
else:
while 1:
try:
_s = yield _y
except GeneratorExit as _e:
try:
_m = _i.close
except AttributeError:
pass
else:
_m()
raise _e
except BaseException as _e:
_x = sys.exc_info()
try:
_m = _i.throw
except AttributeError:
raise _e
else:
try:
_y = _m(*_x)
except StopIteration as _e:
_r = _e.value
break
else:
try:
if _s is None:
_y = next(_i)
else:
_y = _i.send(_s)
except StopIteration as _e:
_r = _e.value
break
return _r
def get_em():
# fibs = fibo(0,1)
# yield from fibs # delegates to subgenerator
# return fibs
return pep380(fibo(0,1))
g = get_em()
print(tuple(takewhile(lambda n: n < 1000, g)))
Console output:
(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987)
Now if I comment out differently:
def get_em():
fibs = fibo(0,1)
yield from fibs # delegates to subgenerator
# return fibs
# return pep380(fibo(0,1))
Same answer:
(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987)
One may also return fibs directly from get_em, showing that 'yield from' is
driving the same process i.e. delegation is happening.
Just scratching the (itchy) surface.
Kirby
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20160104/a248d86e/attachment.html>
More information about the Edu-sig
mailing list