__next__ and StopIteration

Ned Batchelder ned at nedbatchelder.com
Mon Feb 9 20:30:21 EST 2015


On 2/9/15 2:24 PM, Ned Batchelder wrote:
> On 2/9/15 2:14 PM, Charles Hixson wrote:
>> I'm trying to write a correct iteration over a doubly indexed container,
>> and what I've got so far is:    def __next__ (self):
>>          for row    in    range(self._rows):
>>              for col in range(self._cols):
>>                  if self._grid[row][col]:
>>                      yield    self._grid[row][col]
>>                  #end    if
>>              #end    for col
>>          #end    for row
>>          raise    StopIteration
>>
>> What bothers me is that it doesn't look like it would continue to raise
>> StopIteration if it were called again, which is what
>> https://docs.python.org/3/library/stdtypes.html#iterator.__next__ says
>> is correct.  How should this be fixed?
>
> You are using yield, which means __next__ is a generator.  As such, you
> don't have to explicitly raise StopIteration at all.  Just remove that
> statement, and you should be fine.
>
> Also, look into how you are posting, the code is nearly mangled. :(
>

Oops, __next__ isn't right here, it should be __iter__:

     def __iter__(self):
         for row in range(self._rows):
             for col in range(self._cols):
                 if self._grid[row][col]:
                     yield self._grid[row][col]

-- 
Ned Batchelder, http://nedbatchelder.com




More information about the Python-list mailing list