Skip to content

Inconsistent behaviour of generators #145503

@bartolini

Description

@bartolini

Bug report

Bug description:

from typing import Any, Generator, Iterable


def main() -> None:
    test_data = (1, 2, 3, 4, 5)

    print("(1) data -->", test_data)
    print("(1) result -->", one_way := list(walk(test_data)))

    next(gen_walk := walk_another_way())
    gen_walk.send(test_data)
    print("(2) result -->", another_way := list(gen_walk))

    assert one_way == another_way, "the results are different"


def walk(data: Iterable[Any]) -> Generator[Any, None, None]:
    for value in data:
        print("    yield -->", value)
        yield value


def walk_another_way() -> Generator[Any, Any, None]:
    data = yield
    print(f"(2) data -->", data)
    yield from walk(data)


if __name__ == "__main__":
    main()

I would expect both results, one_way and another_way, to be the same, however the second generator walk_another_way() is returning a result that is missing the very first value.

Here is the output of this short program:

bart@think-bart:~/Temp$ python3 test.py 
(1) data --> (1, 2, 3, 4, 5)
    yield --> 1
    yield --> 2
    yield --> 3
    yield --> 4
    yield --> 5
(1) result --> [1, 2, 3, 4, 5]
(2) data --> (1, 2, 3, 4, 5)
    yield --> 1
    yield --> 2
    yield --> 3
    yield --> 4
    yield --> 5
(2) result --> [2, 3, 4, 5]
Traceback (most recent call last):
  File "/home/bart/Temp/test.py", line 30, in <module>
    main()
  File "/home/bart/Temp/test.py", line 14, in main
    assert one_way == another_way, "the results are different"
           ^^^^^^^^^^^^^^^^^^^^^^
AssertionError: the results are different

CPython versions tested on:

3.14

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingThe issue will be closed if no feedback is providedtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions