I’m a big fan of Python’s for…else syntax – it’s surprising how often it’s applicable, and how effectively it can simplify code.
However, I’ve not figured out a nice way to use it in a generator, for example:
def iterate(i): for value in i: yield value else: print 'i is empty'
In the above example, I’d like the print statement to be executed only if i is empty. However, as else only respects break and return, it is always executed, regardless of the length of i.
If it’s impossible to use for...else in this way, what’s the best approach to this so that the print statement is only executed when nothing is yielded?
You’re breaking the definition of a generator, which should throw a StopIteration exception when iteration is complete (which is automatically handled by a return statement in a generator function)
So:
Best to let the calling code handle the case of an empty iterator:
Might be a cleaner way of doing the above, but that ought to work fine, and doesn’t fall into any of the common ‘treating an iterator like a list’ traps below.