[issue8376] Tutorial offers dangerous advice about iterators: “__iter__() can just return self”
loic rowe
report at bugs.python.org
Mon Oct 17 09:14:25 EDT 2016
loic rowe added the comment:
A new proposal is to add at the end of the paragraph on the iterator those point:
"""
As you should have noticed this Reverse let you iterate over the data only once::
>>> rev = Reverse('spam')
>>> for char in rev:
... print(char)
...
m
a
p
s
>>> for char in rev:
... print(char)
...
>>>
So now let's complete our example to have a container that allow you to iterate over his items backwards::
class ReverseList(object):
"Container that lets you iterate over the items backwards"
def __init__(self, data):
self.data = data
def __iter__(self):
return ReverseIterator(self.data)
class ReverseIterator(object):
"Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
>>> rev = ReverseList([1,2,3])
>>> for char in rev:
... print (char)
...
3
2
1
>>> for char in rev:
... print (char)
...
3
2
1
"""
----------
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue8376>
_______________________________________
More information about the Python-bugs-list
mailing list