0

So I am implementing a pathfinding algorithm in python and I want to look how each iteration looks like. So I made it a generator that will yield every intermediate result up until the final result which will end with a return statement.

I made a quick pygame (because I am not aware of python libraries yet, so it was the simplest for me to make a grid and color the cells) program to visualize everything. Every frame makes an iteration on the algorithm and updates a variable result = next(alg). The problem is when the algorithm ends, It still tries to go next. I was wondering if there is a way around this other than catching the stopiteration error. The best for me would be something like if not alg.over() : result = next(alg), but I found nothing on the internet. Is there something like that that I can use? Thank you !

  • 3
    The correct way is to catch the exception. There is no other way. You can iterate through the items in a `for` loop, but internally, that is also going to catch the exception. – zvone Apr 02 '19 at 17:18
  • Perfect then! I just thought there was a more pythonic way than dealing with the exception. Also performance-wise I thought that an if statement would be faster than a try-catch block for every frame. That's also why I can't use a for statement : I need to make one iteration per frame. Thank you, I will just use the try-except method. – Tommy-Xavier Robillard Apr 02 '19 at 17:23
  • 1
    [How can I tell whether a generator was just-started?](https://stackoverflow.com/q/41307038/953482) talks a little bit about inspecting the state of a generator, including whether it's closed. But using `inspect` to look at private-ish attributes isn't particularly idiomatic, so it's more of a curiosity here than a production-quality solution. – Kevin Apr 02 '19 at 17:27
  • On second thought, `inspect.getgeneratorstate` can't tell you the answer to "has this generator yielded its final value, and the next call to `next()` will raise a StopIteration?" because that would require solving the Halting Problem. The best it can do is answer "has this generator already raised StopIteration at least once?" – Kevin Apr 02 '19 at 17:35

0 Answers0