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 expression, 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?