[Tutor] Iterators, example (need help)

Steven D'Aprano steve at pearwood.info
Tue Oct 23 02:43:37 CEST 2012


On 23/10/12 09:30, Bryan A. Zimmer wrote:

> I know there are errors in the program, but I wanted to see if someone
> can tell me something about the iterator "magic" that this program is
> trying to use.

In simple terms: an iterator is a sequence of items that understands
the iterator protocol. If you say to it, "iterator, please give me
the next value", it will respond by giving you the next value in the
sequence.

Of course you don't literally talk to it, you use an object-oriented
method call. Or more frequently, you simply define the appropriate
"magic methods" and let Python handle the rest.

There's nothing that you can do with iterators that can't be done some
other way, but they are a great way to process sequences of data
without needing to accumulate the data up front, such as in a list.
For example, it is trivially easy to produce an iterator that returns
a never-ending stream of data.

Nearly all magic methods in Python have double leading and trailing
underscores. There are lots of them, but 99.9% of the time you don't
explicitly use them *except* to define them in your class. Then you
either iterate over the object:

     for item in some_iterator:
         ...


or occasionally pull out a single item:

     item = next(some_iterator)



Iterators have two "dunder" (Double UNDERscore) magic methods:

__next__
__iter__


In general, your __iter__ method will be trivially simple:

def __iter__(self):
     return self

and most of the logic will be in __next__. I see your __iter__
method is a little more complicated, but I haven't studied it
in detail to see if the extra complication is justified.




-- 
Steven


More information about the Tutor mailing list