generators and exceptions

Clark C. Evans cce at clarkevans.com
Sat Mar 15 16:29:05 EST 2003


Hello, I'm playing with 2.2 generators, and it seems
that they don't like exceptions...

    from __future__ import generators
    class MyExc(Exception): pass
    def mygen(val):
        while val > 0:
           if val % 2: raise MyExc
           yield val
           val =- 1

    iterator = iter(mygen(4))
    while 1:
       try:
          val = iterator.next()
          print val
       except MyExc: pass
       except StopIteration: break


Anyway, this _only_ prints out 4, instead of 4, 2
as I expected.  I expect 4, 2 beacuse an equivalent
iterator would produce 4, 2.  It seems that generators
die on the first exception... is there a way around 
this?  I'm asking beacuse I'm using generators in a
non-blocking database system, where I want to raise
WouldBlock in my generator, but still be able to 
call the generator at a later time when it may 
not block...

Clark
    





More information about the Python-list mailing list