Iterators, iterables and special objects

Peter Slížik peter.slizik at gmail.com
Thu Jul 23 05:14:35 EDT 2020


> Works in what way? You can't use it in a 'for' loop if it doesn't
> define __iter__.
>

class Iterable:
    def __iter__(self):
        return Iterator(...)

class Iterator:
    def __next__(self):
        return <next item>

    # No __iter__ here.
    # I've just forgotten to def it.

With this setup, using for to iterate over Iterable *will* still work,
though you cannot use the trick described below.

> Yes? It is indeed an iterator, since its iter method returns itself. It
is also iterable, since it has an iter method.
Of course, you're right. But you're reading the article through the eyes of
an experienced developer.


> It's so you can do things like this:
>
> def show_with_header(stuff):
>     stuff = iter(stuff)
>     hdr = next(stuff)
>     print(hdr)
>     for line in stuff:
>         print(line)
>         if new_page(): print(hdr)
>

Yes, @Terry had given the same example. Frankly, I didn't know about it
before, I somehow had the misconception that for always got a 'fresh'
iterator...

 Peter


More information about the Python-list mailing list