Visitar URL original
itertools.starmap can fail to construct a proper iterator · Issue #117833 · python/cpython · GitHub
The Wayback Machine - https://web.archive.org/web/20260606021157/https://github.com/python/cpython/issues/117833
Skip to content
/ cpython Public

itertools.starmap can fail to construct a proper iterator #117833

@takuom

Description

@takuom

Bug report

Bug description:

Contrary to what's claimed in the documentation for itertools.starmap, the starmap object m below is not properly an iterator in the sense specified in the documentation. Specifically, m.__next__ keeps returning a value after it raises StopIteration.

from itertools import repeat, starmap

class F:
    def __call__(self):
        if self._a:
            self._a = False
            raise StopIteration

    def __init__(self, /, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._a = True

# Callable object of type `F`
f = F()

# Problematic object
m = starmap(f, repeat([]))

# Exhaust `m`.
[*m]

print(next(m)) # "None"

Compare m with i below.

[*(i := iter(F(), object()))]
next(i) # StopIteration

I understand that starmap(f, repeat([])) should really be an iterator equivalent to iter(f, object()) for every f which makes the latter a valid iterator.

A conceptually better expression by the way for an iterator equivalent to these would be map(f). The documentation actually says that map requires a second argument, so this requirement is technically not a bug of map, but I don't see any advantage of it, and think that it's against natural expectation when map can accept any other number than zero of similar arguments. Note that starmap(f, repeat(seq)) is equivalent to map(f, *map(repeat, seq)) when the sequence seq is non-empty. map(f, *map(repeat, [])) can of course be written simply as map(f). While the expression starmap(f, repeat([])) tells to pass no argument to f each time, the expression map(f) simply doesn't tell to pass any argument.

CPython versions tested on:

3.11

Operating systems tested on:

macOS

Metadata

Metadata

Assignees

Labels

type-bugAn unexpected behavior, bug, or error
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions