1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] try-finally in Python 3 generator

Discussão em 'Python' iniciado por Stack, Setembro 11, 2024.

  1. Stack

    Stack Membro Participativo

    I have met a snippet of Python 3 code:

    def gen():
    try:
    while True:
    yield 1
    finally:
    print("stop")

    print(next(gen()))


    After I run it, I thought at first that the output should be:

    1


    But actually the result is:

    stop
    1


    How can this happen? What happened under the hood?

    If I run for i in gen(): print(i), there will be an infinite loop which is what I expected. What is the difference between for and next here?

    Continue reading...

Compartilhe esta Página