带有生成器表达式的异常广播(Python)

时间:2018-12-09 20:22:33

标签: python exception-handling generator-expression

我遇到了以下行为。使用了具有以下结构的代码块

try:
    tup = tuple(<some_expression> for <_> in <iterator>)
except <SomeException>:
    pass

在元组的生成过程中(在生成器表达式内)引发SomeException时,try-except块不处理它,而是暂停了整个程序。为什么呢?并且有一种方法可以确保在genexpr中遇到的异常。被“广播”到外部范围了?

具体示例

test.py

def input_generator():
    try:
        while True:
            for token in input().split():
                yield token
    except EOFError:
        pass


pyIn = input_generator()


def tuple_gen(n: int):
    try:
        while True:
            yield tuple(next(pyIn) for _ in range(n))
    except StopIteration:
        pass
    except ValueError:
        pass

if __name__ == "__main__":
    for a, b in tuple_gen(2):
        print(a, b)

考虑对tuple_gen生成器的一个实例进行迭代,并以一个空文件作为输入(如stdin)。遇到EOF时,pyIn生成器终止,因此next(pyIn)引发StopIteration,但是程序没有被except块捕获,而是暂停了。

例如,保存一个空的test.txt文件(仅一行),然后在(Windows)控制台上运行该文件

python test.py < test.txt

导致以下回溯:

Traceback (most recent call last):
  File "test.py", line 16, in <genexpr>
    yield tuple(next(pyIn) for _ in range(n))
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "test.py", line 24, in <module>
    for a, b in tuple_gen(2):
  File "test.py", line 16, in tuple_gen
    yield tuple(next(pyIn) for _ in range(n))
RuntimeError: generator raised StopIteration

更新

如timgeb的评论所指出,this问题解释了眼前的问题。

0 个答案:

没有答案