voc icon indicating copy to clipboard operation
voc copied to clipboard

Finally block of generator is not executed during garbage collection

Open BPYap opened this issue 7 years ago • 0 comments

In Python, when a generator object is garbage collected, its finally block will be executed and any print statement in it will be displayed on console.

Consider the python file Test.py below:

def gen():
    try:
       yield "try"
    finally:
       print("finally")

g = gen()
print(next(g))

When it is executed in command line, the output will be:

C:\Users\Desktop>python3 Test.py
try
finally

Similar output is obtained when the code is defined in python 3 interactive shell:

C:\Users\Desktop>python3
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def gen():
...     try:
...             yield "try"
...     finally:
...             print("finally")
...
>>> g = gen()
>>> print(next(g))
try
>>> exit()
finally

The print statement in finally block is executed when the program ends/ the interactive shell exits.

However, when the same program is executed in voc, the finally block is not executed even though a finalize method is defined:

(env) C:\Users\Desktop>voc -v Test.py
Compiling Test.py ...
Writing .\python\Test.class ...

(env) C:\Users\Desktop>java -classpath python-java-support.jar;. python.Test
try

(the finalize method invokes next() on the generator to resume execution, so it should execute the print statement in the generator when garbage collector invokes the finalize method)

BPYap avatar Jun 01 '18 10:06 BPYap