1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] When does python 3 execute the beginning of a generator function?

Discussão em 'Python' iniciado por Stack, Setembro 10, 2025.

  1. Stack

    Stack Membro Participativo

    Python 3 seems not to execute the beginning of a generator function, from its first line up to the first yield at the time when the function is first called. Python seems to defer the initial execution until the first time next(agenerator) is invoked. Is that correct? How does python know to do that?

    Example:

    def fib():
    print("Executing the top of fib")
    a, b = 0, 1
    while True:
    yield a
    a, b = b, a + b


    usage:

    f=fib()
    print("called fib()")
    print([next(f) for i in range( 5)])


    result:

    called fib()
    Executing the top of fib
    [0, 1, 1, 2, 3]

    Continue reading...

Compartilhe esta Página