Exit in while loop generator

I don't understand how to wash 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

Appears when g.close () is called, GeneratorExit is called because "you need to clear it up a bit.", But I don’t understand why RuntimeError exists.

+4
source share
3 answers

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

Yes, GeneratorExit occurs when you call the close () method.

See the following documentation:

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

And the exception will raise a RuntimeError

, , , . , - 9. , RuntimeError. .

+7

, , , - yield .

.

+1

return "Need to do some clean up.". :). , ,

while True:
    try:
        yield 9
     except GeneratorExit:
        print "Need to do some clean up."
        return
+1

Source: https://habr.com/ru/post/1569818/


All Articles