generators and exceptions

Arne Koewing ark at gmx.net
Sun Mar 16 09:17:02 CET 2003


"Clark C. Evans" <cce at clarkevans.com> writes:

> 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...
you may build your own object handling the iterator protocol, 
that wraps up your generator:

from __future__ import generators

class MyExc(Exception): pass

def mygen(val):
    while val >= 0:
        if val % 2:
            yield MyExc()  #yield it don't raise
        else:
            yield val
        val = val - 1
                

class handler:
    def __init__(self,itr):
        self.iterator=itr
    def __getitem__(self,index):
        val=self.iterator.next()
        if isinstance(val,Exception):
            raise val
        return val

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





More information about the Python-list mailing list