Martin Panter added the comment:

What is probably happening here is how garbage collection works at the 
interpreter exit. It is sort of mentioned in the warning at 
<https://docs.python.org/3/reference/datamodel.html#object.__del__>.

The variable g is an iterator for event_gen(), and it is still “alive” when the 
exception is raised. The exception contains a reference to the traceback and 
all the local variables, including g. So the context manager in the generator 
cannot exit until g is deleted [or g.close() is called].

In the “volatile exception” case, I guess it is easy for the interpreter to 
release the exception traceback, including the g iterator that it references, 
straight after it has reported the traceback.

But when you store an exception that you catch in a local variable, you create 
a reference loop (something like ee.__traceback__.tb_frame.f_locals["ee"] is 
ee). So it is not so easy to release the references, and by the time the 
garbage collector runs, I guess it has already set builtin names like “open” 
(global variable of the “builtins” module) to None.

If you need a generator to clean up, you should probably close the generator 
before exiting the function rather than relying on garbage collection. 
Unfortunately there is no mechanism like ResourceWarning to indicate this 
problem with generators.

----------
nosy: +martin.panter

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue26528>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to