generator - In the answer provided except StopIteration hangs indefinitely and delete iterator is out of scope



The previous answer that was posted here How yield catches StopIteration exception? and accepted shows the following:

iterator = iter(iterable)
    while True:
        item = next(iterator)
except StopIteration:
    del iterator

The problem in Python 3.6.4 pass hangs indefinitely never closing out of the program cleanly.

del complains that the iterator is not defined when it is. My assumption is scope changes.

Any ideas how to exit cleanly when StopIteration is raised?

1 Answer: 

Well I realized the loop expression must live inside the try statement only. I attempted to move the loop expression outside of the try catch block and it does hang indefinitely as well change scope when finally portion is executed.

I am sure there is a more formal answer that breaks down scope, exception and raise, etc. I now know there is only way to do this.