Message250460
| Author |
guilimo |
| Recipients |
guilimo |
| Date |
2015年09月11日.10:00:53 |
| SpamBayes Score |
-1.0 |
| Marked as misclassified |
Yes |
| Message-id |
<1441965654.18.0.0798037188462.issue25069@psf.upfronthosting.co.za> |
| In-reply-to |
| Content |
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 |
|
History
|
|---|
| Date |
User |
Action |
Args |
| 2015年09月11日 10:00:54 | guilimo | set | recipients:
+ guilimo |
| 2015年09月11日 10:00:54 | guilimo | set | messageid: <1441965654.18.0.0798037188462.issue25069@psf.upfronthosting.co.za> |
| 2015年09月11日 10:00:54 | guilimo | link | issue25069 messages |
| 2015年09月11日 10:00:53 | guilimo | create |
|