Skip to content
This repository has been archived by the owner. It is now read-only.

Finally block of generator is not executed during garbage collection #828

Open
BPYap opened this issue Jun 1, 2018 · 0 comments
Open

Finally block of generator is not executed during garbage collection #828

BPYap opened this issue Jun 1, 2018 · 0 comments

Comments

@BPYap
Copy link
Contributor

@BPYap BPYap commented Jun 1, 2018

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 BPYap changed the title Finally block is not executed during garbage collection Finally block of generator is not executed during garbage collection Jun 1, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
1 participant