Search code examples
pythonpython-2.7generator

Python execute code only if for loop did not begin iteration (with generator)?


The else block in a for/else clause gets executed if the iteration finishes but is not interrupted by break, so I read.

Is there a language construct which would let me write something which executes only if the for loop did not begin iteration? If I was using a tuple or list, I would do something like this:

if seq:
    for x in seq:
         # something
else:
    # something else

But when I use a generator, I don't get the behavior I want:

>>> g = (x for x in range(2))
>>> for x in g:
...     print x
... else:
...     print "done"
... 
0
1
done    # I don't want "done" here
>>> g = (x for x in range(2) if x > 1)
>>> if g:
...     for x in g:
...         print x
... else:
...     print "done"
... 
>>>     # I was expecting "done" here

How can I do this without exhausting creating a tuple or a list from the generator, while also using a for loop? I could use next() in a while loop and try to catch StopIteration, but I'd like to see if there's a nice way to do it with for.


Solution

  • I can't think of a better way than updating a boolean inside the for loop.

    any_results = False
    for x in g:
        any_results = True
        print x
    if not any_results:
        print 'Done'