Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GeneratorExit in while loop

Tags:

python

I am not clear about the behavior of catching GeneratorExit in a while loop, here is my code:

# python 
Python 2.6.6 (r266:84292, Sep  4 2013, 07:46:00) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def func():
...     while True:
...         try:
...             yield 9
...         except GeneratorExit:
...             print "Need to do some clean up."
... 
>>> g = func()
>>> g.next()
9
>>> g.close()
Need to do some clean up.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: generator ignored GeneratorExit

It appears when g.close() is called, GeneratorExit is catched because "Need to do some clean up." is printed, but I do not understand why there is a RuntimeError.

like image 864
Eric Avatar asked Jan 03 '15 14:01

Eric


2 Answers

"It appears when g.close() is called, GeneratorExit is catched"

Yes, GeneratorExit is raised when the generator's close() method is called.

See the following documentation:

https://docs.python.org/2/library/exceptions.html

And the exception will cause a RuntimeError

After the aforementioned exception is raised inside the loop, it is actually handled, and you see the printed error message. But, the loop continues, and it still tries to yield 9. That's when you see the RuntimeError. Therefore, moving the exception handling outside of your loop solves the problem.

like image 62
Jobs Avatar answered Oct 05 '22 23:10

Jobs


Just add a return statement after printing "Need to do some clean up.". Everything works fine then :). This the preferred way, esp when you cannot move your exception out

while True:
    try:
        yield 9
     except GeneratorExit:
        print "Need to do some clean up."
        return
like image 25
nesdis Avatar answered Oct 05 '22 22:10

nesdis