python - Python 中的停止迭代

标签 python exception generator stopiteration

我在阅读Python函数式编程时遇到问题。

def get_log_lines(log_file): 
    line = read_line(log_file) 
    while True:
        try:
            if complex_condition(line):
                yield line
            line = read_line(log_file)
        except StopIteration:
            raise

添加 try... except 语句以包围 read_line。为什么不让 read_line 抛出 StopIteration 异常,如下所示:

def get_log_lines(log_file): 
    line = read_line(log_file) 
    while True:
        if complex_condition(line):
            yield line
        line = read_line(log_file)

最佳答案

我认为没有任何理由将try... except保留在那里。例如,重新加注仍将带有相同的回溯,因此生成器的行为不会改变。

换句话说,它在那里毫无意义,可能是重构留下的产物。

您可以进一步简化循环,删除多余的第一行:

def get_log_lines(log_file): 
    while True:
        line = read_line(log_file) 
        if complex_condition(line):
            yield line

关于python - Python 中的停止迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32648006/

相关文章:

python - 使用管道进行多重处理 - 应用程序总是在大约 5 分钟后停止

.net - ClickOnce 应用程序调试中的 "Store metadata "CurrentBind "is not valid"

android 应用程序崩溃 NetworkOnMainThreadException

c# - MongoDB C# 身份验证异常

python - App Engine 搜索 API - 暂时错误

python - 根据 Pandas 中的组大小对分组数据进行排序

带有列表和追加的 Python 奇怪行为

python - 生成器函数在内部是如何工作的?

Python:复杂的迭代

python - Typing.Generator 的第二个和第三个类型参数是什么意思?