Message from exception raised in generator disappears

Jeff Epler jepler at unpythonic.net
Sun Oct 17 04:08:47 CEST 2004


>>> def gx():
...     yield 1
...     raise RuntimeError
... 
>>> list(gx())
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in gx
RuntimeError

Exceptions in generators work for me.  Maybe there's another problem
with your code.

Jeff
PS Here's my stab at writing your function, which seems like a useful
one.

By explicitly converting s to an iterator before the loop, I can also
call "next" on it to consume an additional item on this pass through the
loop.  The use of unicode literals (instead of decimal values) for
comparison may give a slight speed boost, because it avoids an ord()
call on each trip through the loop.  I doubt you can measure the speed
difference of 'c1 <= x < c2' and 'c1 <= x and x < c2' but I think it
reads better.  The try/except StopIteration part is unfortunate, but I
don't see how to avoid it.  Whether it beats having a separate
'surrogate' variable and more complicated flow control I'm not sure.
(the exception will be seen 0 times in the try: block in a "correct"
string, and only once in a "proper" string, so it can't be that bad...)

def chars(s):
    s = iter(s)
    for i in s:
        if u'\ud800' <= i < u'\udc00':
            try:
                j = s.next()
            except StopIteration:
                raise ValueError("Bad pair: string ends after %r" % i)
            if u'\udc00' <= j < u'\ue000':
                yield i + j
            else:
                raise ValueError("Bad pair: %r (no second half)" % (i+j))
        elif u'\udc00' <= i < u'\ude00':
                raise ValueError("Bad pair: %r (no first half)" % i)
        else:
            yield i
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20041016/50df907c/attachment.pgp>


More information about the Python-list mailing list