When I use a generator in a for loop, it seems to \"know\", when there are no more elements yielded. Now, I have to use a generator WITHOUT a for loop, and use next
This may not precisely answer your question, but I found my way here looking to elegantly grab a result from a generator without having to write a try:
block. A little googling later I figured this out:
def g():
yield 5
result = next(g(), None)
Now result
is either 5
or None
, depending on how many times you've called next on the iterator, or depending on whether the generator function returned early instead of yielding.
I strongly prefer handling None
as an output over raising for "normal" conditions, so dodging the try/catch here is a big win. If the situation calls for it, there's also an easy place to add a default other than None
.