Let us suppose we have a generator function gen()
, which we do not know if it is empty or not.
If it is empty, we would like to execute a special function foo()
, and otherwise we would like to execute a function over each element of the iterator bar(elem)
.
I can do it like this:
is_empty = True
for elem in gen():
is_empty = False
bar(elem)
if is_empty: foo()
But that does not feel very pythonic. Any other approach?
You can't tell directly whether a generator is empty. This is by design. A key principle behind generators is they do not hold in memory all items of a generated sequence.
But you can do something like this:
from itertools import chain
def check_first_and_iterate(iterable):
try:
first = next(iterable)
for item in chain([first], item):
bar(item)
except StopIteration:
foo()
check_first_and_iterate(iterable)