1

I have code similar to this structure:

def my_gen(some_str):
    if some_str == "":
        raise StopIteration("Input was empty")
    else:
        parsed_list = parse_my_string(some_str)
        for p in parsed_list:
            x, y = p.split()
            yield x, y

for x, y in my_gen()
    # do stuff
    # I want to capture the error message from StopIteration if it was raised manually

Is it possible to do this by using a for loop? I couldn't find a case similar to this elsewhere. If using a for loop isn't possible, what are some other alternatives?

Thanks

Mo2
  • 1,090
  • 4
  • 13
  • 26
  • 2
    Why not raise a different kind of error like a `ValueError` maybe? that way you can do a `try .. except ValueError: ..` – ashwinjv Aug 26 '15 at 19:30
  • @hgwells I thought about that shortly before you mentioned it. After thinking about it some more, I couldn't find a reason not to do what you suggested. Not sure if I should delete the question now. – Mo2 Aug 26 '15 at 20:00
  • The tupel for `yield` seems to be missing a second value. And the `else` branch could be a one liner: `return (p.split() for p in parse_my_string(some_str))` – BlackJack Aug 26 '15 at 22:50
  • @BlackJack the missing value is a typo. Thanks. The rest of the code was shortened just to get the point across. The actual code is a bit longer. – Mo2 Aug 27 '15 at 14:53

1 Answers1

5

You cannot do this in a for loop - because a for loop will implicitly catch the StopIteration exception.

One possible way to do this is with an infinite while:

while True:
    try:
        obj = next(my_gen)
    except StopIteration:
        break

print('Done')

Or you can use any number of consumers from the itertools library - have a look at the recipe section at the bottom for examples.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284