How can I skip a generator? I thought about this:
gen = function_that_returns_a_generator(param1, param2) if gen: # in case the generator is null while True: try: print gen.next() except StopIteration: break
Is there a more pythonic way?
Simply
for x in gen: # whatever
will do the trick. Note that if gen always returns True .
if gen
True
for item in function_that_returns_a_generator(param1, param2): print item
You do not need to worry about the test to find out if there is anything returned by your function, as if nothing returned, you will not enter the loop.
Just treat it like any other iterable:
for val in function_that_returns_a_generator(p1, p2): print val
Note that if gen: will always be True, so this is a false test
if gen:
If you do not need the output of the generator because you only care about its side effects, you can use the following single-line:
for _ in gen: pass
You can simply skip it:
>>> gen = (i for i in range(1, 4)) >>> for i in gen: print i 1 2 3
But keep in mind that you can loop only once. The following time generator will be empty:
>>> for i in gen: print i >>>
If you want to manually move the generator (i.e., work with each cycle manually), you can do something like this:
from pdb import set_trace() for x in gen: set_trace() #do whatever you want with x at the command prompt #use pdb commands to step through each loop of the generator eg, >>c #continue