Search code examples
pythongenerator

How to detect generator end explicitly in Python?


I wrote a generator, which returns tuple of values:

import numpy as np

def mygenerator():
    data = np.arange(10)
    data = np.reshape(data, (-1, 2))
    for row in data:
        yield row[0], row[1]

generator = mygenerator()
while True:
    a, b = generator.__next__()
    print("a: ", a, "b: ", b)

and want to use it without for ... in. How detect end of generation then?


Solution

  • The generator will throw an exception StopIteration when it is exhausted. You can catch the exception with tryexcept statement and exit loop when it occurs:

    while True:
        try:
            a, b = next(generator)
        except StopIteration:
            break
        print("a: ", a, "b: ", b)
    

    BTW, why not for loop? It seems that:

    for a, b in generator:
        print("a: ", a, "b: ", b)
    

    does exactly what you want, without cumbersome constructions.