[Python] Why does an integer inside a generator function swallow the object of send()?

Discussão em 'Python' iniciado por Stack, Fevereiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    I am not trying to achieve anything -- apart from learning how generator functions and coroutines work on a brick level, which I am not really getting yet, despite lots of reading....

    $cat test.py

    #No integer
    def eee():
    num = yield
    print(f"First num: {num}")
    num = yield
    print(f"Second num: {num}")
    num = yield
    print(f"Third num: {num}")

    #integer
    def ddd():
    yield 100
    num = yield
    print(f"First num: {num}")
    num = yield
    print(f"Second num: {num}")
    num = yield
    print(f"Third num: {num}")

    e=eee()
    e.send(None)
    e.send(1)
    e.send(2)
    try:
    e.send(3)
    except StopIteration as e:
    print(f'Done with e: {e}\n')

    d=ddd()
    print(d.send(None))
    d.send(1)
    d.send(2)
    d.send(3)

    $python3 test.py
    First num: 1
    Second num: 2
    Third num: 3
    Done with e:

    100
    First num: 2
    Second num: 3


    why does d swallow the num 1?

    Continue reading...

Compartilhe esta Página