如何在 StopIteration 之前停止在生成器上调用 next()

How to stop calling next() on a generator before StopIteration

我有一个调用 API 并生成数据的函数。后来我使用 next() 从生成器中检索数据,但是由于我不知道要“提取”多少数据,所以我最终执行 next() 直到它引发 StopIteration 例外。

def get_data():
    source = API_Instance()
    yield source.get_some_data()

def parse_data():
    data = get_data()
    while True:
        try:
            row_data = next(data)
            print(row_data)
        except StopIteration:
            break

这似乎是一种糟糕的方式。我有办法避免 Try/Except 块吗?就像知道发电机已耗尽的方法一样? (找不到更好的词来形容它

StopIteration异常迭代器如何报告它已经完成。不过,有一种更简单的方法可以遍历整个迭代器:

def parse_data():
    data = get_data()

    for row_data in data:
        print(row_data)