[Python-ideas] Suggested MapView object (Re: __len__() for map())

Chris Angelico rosuav at gmail.com
Wed Dec 12 23:45:09 EST 2018

On Thu, Dec 13, 2018 at 3:07 PM Chris Barker - NOAA Federal via
Python-ideas <python-ideas at python.org> wrote:
> >>> and the test for an iterator is:
> >>>
> >>>   obj is iter(obj)
> Is that a hard and fast rule? I know it’s the vast majority of cases,
> but I imagine you could make an object that behaved exactly like an
> iterator, but returned some proxy object rather that itself.
> Not sure why one would do that, but it should be possible.

Yes, it is.


For an iterable, __iter__ needs to return an appropriate iterator. For
an iterator, __iter__ needs to return self (which is, by definition,
the "appropriate iterator").

Note also that the behaviour around StopIteration is laid out there,
including that an iterator whose __next__ has raised SI but then
subsequently doesn't continue to raise SI is broken. (Though it *is*
legit to raise StopIteration with a value the first time, and then
raise a vanilla SI subsequently. Generators do this, rather than
retain the return value indefinitely.)


More information about the Python-ideas mailing list