[Python-ideas] Generators are iterators

Alexander Belopolsky alexander.belopolsky at gmail.com
Fri Dec 12 21:14:44 CET 2014

On Fri, Dec 12, 2014 at 3:06 PM, Alexander Belopolsky <
alexander.belopolsky at gmail.com> wrote:

> On Fri, Dec 12, 2014 at 2:28 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
>> > 3) there are essentially two (and a half) ways for python code authors
>> to write their own, custom TIIP:
>> >   1) write a class that has a __iter__ and __next__ methods that "do
>> the right thing"
>> >   2a) write a generator function
>> >   2b) write a generator expression
>>     3) write a class with __getitem__ that supports integer indexing
> This gets you a custom iterable.  The corresponding iterator will be the
> buitin iterator type:
> >>> class X:
> ...   __getitem__ = None
> ...
> >>> iter(X())
> <iterator object at 0x10b2a70b8>

The same logic applies to generators and I think this misconception is at
the root of the confusion in this thread.   When you are writing a
generator function, you are not creating a custom TIIP.  You are writing a
code object that Python knows how to convert into an instance of a built-in
TIIP (the generator type).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141212/6d3c9496/attachment.html>

More information about the Python-ideas mailing list