[Python] how come the finally block runs after the result in this code?

Discussão em 'Python' iniciado por Stack, Dezembro 30, 2024.

  1. Stack

    Stack Membro Participativo

    def tricky_generator(n):
    for i in range(n):
    try:
    if i % 2 == 0:
    yield i // 2
    else:
    raise ValueError(f"Odd value: {i}")
    except ValueError as e:
    print(e)
    yield -1
    finally:
    print(f"Finally block executed for i={i}")

    gen = tricky_generator(5)
    result = [next(gen) for _ in range(5)]
    print("Result:", result)


    The result is supposed to be printed at the end, but somehow a finally block i = 4 is executed after it for some reason even though all the finally blocks should be executed before the result

    Continue reading...

Compartilhe esta Página