__next__ and StopIteration

Chris Angelico rosuav at gmail.com
Tue Feb 10 01:38:52 EST 2015


On Tue, Feb 10, 2015 at 5:16 PM, Charles Hixson
<charleshixsn at earthlink.net> wrote:
> Yes, rows and cols are lists, but I'm going to need to iterate through them
> more than once.  I'd rather do without a included class, but if a properly
> formed iterator can only be cycled through once, and if I understand
> properly that means I can't use the "class instance is it's own iterator"
> form.

When you write __iter__ as a generator function, what you actually
have is a factory for iterator objects. (Generators are iterators.)
When something calls __iter__ on your Grid, it gets back a brand new
iterator which is independent of every other iterator from that or any
other Grid, so you can iterate over the same Grid more than once.
You're not writing __next__ here, so you're not using the class
instance as its own iterator, which means that that consideration
doesn't apply.

ChrisA



More information about the Python-list mailing list