python-处理在gen中引发的异常

我有一个生成器和一个使用它的函数:

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)

但这对我来说看起来很尴尬。

georg asked 2020-07-06T15:29:11Z
4个解决方案
51 votes

当生成器引发异常时,它将退出。 您不能继续使用它生成的项目。

例:

>>> 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

如果控制生成器代码,则可以处理生成器内部的异常; 如果不是,则应尝试避免发生异常。

Sven Marnach answered 2020-07-06T15:29:30Z
8 votes

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

我要做的是从生成器中获取isinstanceException,然后将其提升到其他位置。 喜欢:

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检查产生的结果。 我不喜欢可以产生不同类型结果的生成器,但是将其用作最后的选择。

dojuba answered 2020-07-06T15:29:59Z
4 votes

我已经需要解决几次这个问题,并且在寻找其他人做了什么之后才提出这个问题。


投掷而不是提高

一个选项(需要一点点重构)是handler()生成器中的异常(另一个错误处理生成器),而不是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

但是,这样做的缺点是,您仍然必须将通用handler()处理程序放在可能会产生错误的生成器内部。 解决这个问题是不可能的,因为在生成器中引发任何异常都会将其关闭。


一个想法的核心

最好有某种handler()语句,该语句允许生成器在引发错误后继续运行。 然后,您可以编写如下代码:

@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
Rick Teachey answered 2020-07-06T15:31:04Z
1 votes

在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
Sergey Nevmerzhitsky answered 2020-07-06T15:31:30Z
translate from https://stackoverflow.com:/questions/11366064/handle-an-exception-thrown-in-a-generator