I wrote a test program about Python generator. But I got an error that is not expected. And I don't know how to explain it. Let me show you the code:
def countdown(n):
logging.debug("Counting down")
while n > 0:
try:
yield n
except GeneratorExit:
logging.error("GeneratorExit")
n -= 1
if __name__ == '__main__':
c = countdown(10)
logging.debug("value: %d", c.next())
I thought it should run without any problem. But the output is:
# ./test.py
[2015/06/16 04:10:49] DEBUG - Counting down
[2015/06/16 04:10:49] DEBUG - value: 10
[2015/06/16 04:10:49] ERROR - GeneratorExit
Exception RuntimeError: 'generator ignored GeneratorExit' in <generator object countdown at 0x7f9934407640> ignored
Why is there an error at the last line. I don't know why I triggered the GeneratorExit exception. Is there something aobut generator I missed? I also typed the code into interactive python shell, and everything is OK. How can this happen?
When the generator object is garbage-collected at the end of your program, its
close()
method is called, and this raises theGeneratorExit
exception inside the generator. Normally this is not caught and causes the generator to exit.Since you catch the exception and proceed to yield another value, this causes a
RuntimeError
. If you catch theGeneratorExit
exception you need to either reraise it, or exit the function without yielding anything else.