4

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?

Dims
  • 42,427
  • 94
  • 291
  • 543

3 Answers3

18

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.

Błotosmętek
  • 12,365
  • 18
  • 29
  • 6
    This is Stackoverflow: if you write complex example, you told to make it short, if you write short example you told to use simple code suitable for that short example :) – Dims Sep 12 '17 at 10:02
  • 2
    I can't use `for ... in` because in my real code I use complex processing of returned values and switching different loops... – Dims Sep 12 '17 at 10:03
0

Another possibility would be by using the default parameter of next built-in function as a breaking condition. Once the generator is exhausted, instead of throwing a StopIteration exception, the default value will be emitted.

# ...

gen = mygenerator()

stop_value = None # or another value
while True:
    v = next(gen, stop_value)
    if v is stop_value:
        break
    print("a: {}, b: {}".format(*v))
cards
  • 2,194
  • 1
  • 3
  • 21
-1

Stumped into this and suggest do following, generator will exhaust until next() returns None:

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()
a, b = next(generator, None)
while a and b:
    print("a: ", a, "b: ", b)
    a, b = next(generator, None)
Greenonline
  • 1,265
  • 6
  • 21
  • 27
jaydrill
  • 44
  • 7