Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #85419
| From | Ned Batchelder <ned@nedbatchelder.com> |
|---|---|
| Subject | Re: __next__ and StopIteration |
| Date | 2015-02-09 20:30 -0500 |
| References | <54D9072F.3010904@earthlink.net> <mbb1gk$i4b$1@ger.gmane.org> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.18587.1423531834.18130.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: __next__ and StopIteration Ned Batchelder <ned@nedbatchelder.com> - 2015-02-09 20:30 -0500
csiph-web