Comment

Yao

This is because you hold a reference (i.e., pump4) to the generator, thus it cannot be garbage collected. GeneratorExit is raised when the generator is about to be destroyed. That's what I'm assumed.

Parent comment

Don Heidrich

The GeneratorExit seems to get lost when using a factory approach. I changed the pump definition in "The Solution" to accept a dummy var and then reference the generator as follows. I'm running Python 3.7.4. I'm wondering if this is expected behavior and I am confused, and/or maybe my approach is incorrect. def pump(dummy): numbers = [1, 2, 3, 4] try: for number in numbers: yield number print("Have sent", number) except GeneratorExit: print("Exception!") print("Last number was sent") pump4 = pump(4) for number in pump4: print("Got", number) if number == 2: break print("All done") Got 1 Have sent 1 Got 2 All done >>> # BUT THIS WORKS! for number in pump(4): print("Got", number) if number == 2: break print("All done") Got 1 Have sent 1 Got 2 Exception! Last number was sent All done >>>