Handle an exception thrown in a generator

前端 未结 4 734
猫巷女王i
猫巷女王i 2020-12-01 13:23

I\'ve got a generator and a function that consumes it:

def read():
    while something():
        yield something_else()

def process():
    for item in read         


        
4条回答
  •  借酒劲吻你
    2020-12-01 14:13

    This is also something that I am not sure if I handle correctly/elegantly.

    What I do is to yield an Exception from the generator, and then raise it somewhere else. Like:

    class myException(Exception):
        def __init__(self, ...)
        ...
    
    def g():
        ...
        if everything_is_ok:
            yield result
        else:
            yield myException(...)
    
    my_gen = g()
    while True:
        try:
            n = next(my_gen)
            if isinstance(n, myException):
                raise n
        except StopIteration:
            break
        except myException as e:
            # Deal with exception, log, print, continue, break etc
        else:
            # Consume n
    

    This way I still carry over the Exception without raising it, which would have caused the generator function to stop. The major drawback is that I need to check the yielded result with isinstance at each iteration. I don't like a generator which can yield results of different types, but use it as a last resort.

提交回复
热议问题