Skip to content

map and accumulate creates broken iterator when a StopIteration is raised from the callback function #137921

@Atry

Description

@Atry

Bug report

Bug description:

def conditional_raise_stop_iteration(i: int):
    if i == 3:
        raise StopIteration
    return i

iterator = map(conditional_raise_stop_iteration, range(5))


print(f"Consuming the iterator: {tuple(iterator)}")
print(f"Consuming the iterator again: {tuple(iterator)}")

Expected behavior

When consuming the iterator again, it should not yield any elements, because it is already exhausted

Actual output

Consuming the iterator: (0, 1, 2)
Consuming the iterator again: (4,)

This is a violation of the document:
https://docs.python.org/3/library/stdtypes.html#iterator.__next__

Once an iterator’s next() method raises StopIteration, it must continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken.

This behavior was discussed at maxfischer2781/asyncstdlib#175, where @maxfischer2781 pointed out that the behavior is a violation of the data model.

CPython versions tested on:

3.13

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)pendingThe issue will be closed if no feedback is provided

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions