Search code examples
pythongeneratortry-finally

Execution order with try-finally in python generator functions


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"?


Solution

  • You can rewrite the line print(next(gen())) as

    g = gen()  # temporary variable
    val = next(g)
    #          # the generator is now deleted because the variable g is not referenced anymore
    del(g)     # that calls the "finally" block `print("finally")`
    print(val)
    

    If 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!