pythonpython-3.xgenerator

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


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)


Solution

  • The StopIteration exception is how the iterator reports that it’s done. There is an easier way to loop over an entire iterator, though:

    def parse_data():
        for row_data in get_data():
            print(row_data)