I\'ve got a generator and a function that consumes it:
def read():
while something():
yield something_else()
def process():
for item in read
This is also something that I am not sure if I handle correctly/elegantly.
What I do is to yield an Exception from the generator, and then raise it somewhere else. Like:
class myException(Exception):
def __init__(self, ...)
...
def g():
...
if everything_is_ok:
yield result
else:
yield myException(...)
my_gen = g()
while True:
try:
n = next(my_gen)
if isinstance(n, myException):
raise n
except StopIteration:
break
except myException as e:
# Deal with exception, log, print, continue, break etc
else:
# Consume n
This way I still carry over the Exception without raising it, which would have caused the generator function to stop. The major drawback is that I need to check the yielded result with isinstance at each iteration. I don't like a generator which can yield results of different types, but use it as a last resort.