Skip to content

Return type for iter() and aiter() too strict #6030

@brettcannon

Description

@brettcannon

The definition of builtins.iter() has it returning typing.Iterator:

def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ...

The problem is typing.Iterator requires both __iter__ and __next__:

typeshed/stdlib/typing.pyi

Lines 191 to 194 in 4c6e98e

class Iterator(Iterable[_T_co], Protocol[_T_co]):
@abstractmethod
def __next__(self) -> _T_co: ...
def __iter__(self) -> Iterator[_T_co]: ...

The docs for iter() does not suggest that the returned iterator must define __iter__. And if you look at the implementation of iter() -- as well as PyObject_GetIter() and PyIter_Check() which iter() uses -- there is no requirement that the returned iterator define __iter__.

All of this also applies to aiter() in regards to __aiter__.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions