[Python-iterators] RE: PEP 255: Simple Generators
Michael Hudson
mwh at python.net
Fri Jun 15 19:21:20 EDT 2001
(I'm following up in an odd place for no good reason, in case you have
a mail client that can tell and were wondering).
I think the PEP could use a little discussion about the interactions
between yielding and try/except/finally blocks. What actually happens
is the only plausible behaviour, but I'm not sure I'd see that if I
wasn't already pretty familiar with Python internals.
Here's a fun example if you're on Unix:
->> import termios, tty, select, errno, os
/>> def gen():
|.. try:
|.. term = termios.tcgetattr(0)
|.. tty.setraw(0)
|.. while 1:
|.. try:
|.. r, w, e = select.select([0],[],[])
|.. if 0 in r:
|.. c = os.read(0,1)
|.. if c == '\004': # control-D
|.. return
|.. else:
|.. yield c
|.. except OSError, err:
|.. if err.errno == errno.EINTR:
|.. pass
|.. else:
|.. return
|.. finally:
|.. termios.tcsetattr(0, termios.TCSADRAIN, term)
\__
"list(gen)" is a good way to drive it; type that and batter some keys,
then press control-d.
Arguably the try/finally should be around the call to os.read, and not
contain the yield. It depends on what you're doing with the generator
I guess.
Also:
->> import keyword
->> 'yield' in keyword.kwlist
0
But, generally speaking, I like.
Cheers,
M.
More information about the Python-list
mailing list