New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

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

Comments

Projects
None yet
1 participant
@BPYap
Contributor

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 from Finally block is not executed during garbage collection to Finally block of generator is not executed during garbage collection Jun 1, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment