[New-bugs-announce] [issue25069] Clean issue when generator not exhausted (garbage collector related?)

guilimo report at bugs.python.org
Fri Sep 11 12:00:54 CEST 2015


New submission from guilimo:

Hello!


I experienced a strange behavior when using a generator, with some code encapsulated in a try/finally clause or a context manager.

If the generator is not exhausted when we leave the script (because normal end of script, uncatched exception, etc...), I expect an internal mechanism to execute properly the finally clause (or __exit__ if context manager).
However, in some specific cases, it seems that this mechanism does not work as expected.


Example
=======

Consider the following code:

import time

def create_generator():
    try:
        yield
    finally:
        time.sleep(2)

ct = create_generator()
ct.next()


If you try to execute it, you will get a:
"Exception AttributeError: "'NoneType' object has no attribute 'sleep'" in <generator object create_generator at 0x7f04ad62c0f0> ignored"



Description
===========

My understanding is the following (but I may be wrong):
At the end of the script, the garbage collector automatically calls the close() method of the generator. As a result, GeneratorExit is raised from the "yield", the finally clause is executed, but for some reason, time does not exist anymore (already collected by the GC?).
If you try just a print "xxx" instead of the time.sleep, it seems that there is not any problem.


Important note:
===============

An other very strange thing:
It seems that if I use an other name than "ct" for the generator, the same exact code runs flawlessly...

You can find attached 3 examples (with try/finally, with a context manager, and with an other name for the generator).

I also found this ticket where some discussion may be related to my situation, even if not describing exactly my current problem:
https://bugs.python.org/issue25014

----------
components: Interpreter Core
files: examples.zip
messages: 250460
nosy: guilimo
priority: normal
severity: normal
status: open
title: Clean issue when generator not exhausted (garbage collector related?)
type: crash
versions: Python 2.7
Added file: http://bugs.python.org/file40436/examples.zip

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue25069>
_______________________________________


More information about the New-bugs-announce mailing list