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

Discussão em 'Python' iniciado por Stack, Julho 7, 2025.

  1. Stack

    Stack Membro Participativo

    I have a function that calls an API and yields the data. Later I use next() to retrieve the data from the generator, however since I don't know how much data there is to be "extracted" I end up executing next() until it raises the StopIteration Exception.

    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


    This seems like an awful way to do it. Is there a way for me to avoid the Try/Except block? Like a way to know that the generator is exhausted? (couldn't find a better word for it)

    Continue reading...

Compartilhe esta Página