def gen():
try:
yield 1
finally:
print("finally")
def main():
print(next(gen()))
This code prints
finally
1
I don't understand the order of execution here. Why is "finally" printed before "1"?
def gen():
try:
yield 1
finally:
print("finally")
def main():
print(next(gen()))
This code prints
finally
1
I don't understand the order of execution here. Why is "finally" printed before "1"?
On
The reason why "finally" is printed before "1" is because the first thing Python does is resolve next(gen()), which involves returning 1 and printing "finally". Once Python is done executing next(gen()), it has printed finally, and has a value of 1. Now, it can resolve print(1), which prints "1".
You can rewrite the line
print(next(gen()))asIf you assign the generator to a variable, but don't delete it then it is recycled at the end of main function. That is what you probably expect.
A generator should be assigned to a variable if you use it by
next(), otherwise there would be no way to use a generator with more items because it would be recycled after the first item!