处理生成器中抛出的异常

时间:2012-07-06 16:21:30

标签: python exception generator

我有一个生成器和一个消耗它的函数:

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

def process():
    for item in read():
        do stuff

如果生成器抛出异常,我想在使用者函数中处理它,然后继续使用迭代器,直到它耗尽为止。请注意,我不希望在生成器中有任何异常处理代码。

我想到了类似的东西:

reader = read()
while True:
    try:
        item = next(reader)
    except StopIteration:
        break
    except Exception as e:
        log error
        continue
    do_stuff(item)

但这对我来说相当尴尬。

4 个答案:

答案 0 :(得分:45)

当生成器抛出异常时,它会退出。您无法继续使用它生成的项目。

示例:

>>> def f():
...     yield 1
...     raise Exception
...     yield 2
... 
>>> g = f()
>>> next(g)
1
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in f
Exception
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

如果您控制生成器代码,则可以在生成器内处理异常;如果没有,你应该尽量避免发生异常。

答案 1 :(得分:7)

这也是我不确定我是否正确/优雅地处理的事情。

我所做的是从yield Exception来自生成器,然后将其提升到其他地方。像:

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

这样我仍然可以在没有提升的情况下继续执行Exception,这会导致生成器功能停止。主要缺点是我需要在每次迭代时用isinstance检查产生的结果。我不喜欢能产生不同类型结果的发电机,但将其作为最后的手段使用。

答案 2 :(得分:4)

我需要解决这个问题几次,并在搜索了其他人做过的事后发现了这个问题。

投掷而不是提升

一个选项 - 需要稍微重构一下 - 将throw生成器中的异常(到另一个错误处理生成器)而不是raise它。这可能是这样的:

def read(handler):
    # the handler argument fixes errors/problems separately
    while something():
        try:
            yield something_else()
        except Exception as e:
            handler.throw(e)
    handler.close()

def err_handler():
    # a generator for processing errors
    while True:
        try:
            yield
        except Exception1:
            handle_exc1()
        except Exception2:
            handle_exc2()
        except Exception3:
            handle_exc3()
        except Exception:
            raise

def process():
    handler = err_handler()
    handler.send(None)  # initialize error handler
    for item in read(handler):
        do stuff

这并不总是最好的解决方案,但它肯定是一种选择。

广义解决方案

你可以用装饰器让它变得更好:

class MyError(Exception):
    pass

def handled(handler):
    """
    A decorator that applies error handling to a generator.

    The handler argument received errors to be handled.

    Example usage:

    @handled(err_handler())
    def gen_function():
        yield the_things()
    """
    def handled_inner(gen_f):
        def wrapper(*args, **kwargs):
            g = gen_f(*args, **kwargs)
            while True:
                try:
                    g_next = next(g)
                except StopIteration:
                    break
                if isinstance(g_next, Exception):
                    handler.throw(g_next)
                else:
                    yield g_next
        return wrapper
    handler.send(None)  # initialize handler
    return handled_inner

def my_err_handler():
    while True:
        try:
            yield
        except MyError:
            print("error  handled")
        # all other errors will bubble up here

@handled(my_err_handler())
def read():
    i = 0
    while i<10:
        try:
            yield i
            i += 1
            if i == 3:
                raise MyError()
        except Exception as e:
            # prevent the generator from closing after an Exception
            yield e

def process():
    for item in read():
        print(item)


if __name__=="__main__":
    process()

输出:

0
1
2
error  handled
3
4
5
6
7
8
9

然而,这样做的缺点是你仍然需要在可能产生错误的生成器中放置泛型Exception处理。解决这个问题是不可能的,因为在发电机中引发任何异常都会关闭它。

想法的核心

最好有一些yield raise语句,它允许生成器在引发错误后继续运行。然后你可以写这样的代码:

@handled(my_err_handler())
def read():
    i = 0
    while i<10:
        yield i
        i += 1
        if i == 3:
            yield raise MyError()

...而handler()装饰器可能如下所示:

def handled(handler):
    def handled_inner(gen_f):
        def wrapper(*args, **kwargs):
            g = gen_f(*args, **kwargs)
            while True:
                try:
                    g_next = next(g)
                except StopIteration:
                    break
                except Exception as e:
                    handler.throw(e)
                else:
                    yield g_next
        return wrapper
    handler.send(None)  # initialize handler
    return handled_inner

答案 3 :(得分:2)

在Python 3.3之后,用于捕获来自原始生成器的异常的代码将非常简单:

from types import GeneratorType


def gen_decorator(func):
    def gen_wrapper(generator):
        try:
            yield from generator  # I mean this line!
        except Exception:
            print('catched in gen_decorator while iterating!'.upper())
            raise

    def wrapper():
        try:
            result = func()

            if isinstance(result, GeneratorType):
                result = gen_wrapper(result)

            return result
        except Exception:
            print('catched in gen_decorator while initialization!'.upper())
            raise

    return wrapper

用法示例:

@gen_decorator
def gen():
    x = 0
    while True:
        x += 1

        if x == 5:
            raise RuntimeError('error!')

        yield x


if __name__ == '__main__':
    try:
        for i in gen():
            print(i)

            if i >= 10:
                print('lets stop!')
                break
    except Exception:
        print('catched in main!'.upper())
        raise