Bug in Tutorial - 9.Classes - 9.8 Iterators - Definition of __iter__() non reusable

Good morning, In the tutorial Docs, chapter 9 (Clases), section 9.8 (Iterators)... (this is the link 9. Classes - Python 3.12.7 documentation<https://docs.python.org/3/tutorial/classes.html#iterators>) ...there is an example of __iter__() and __next__() methods explaining the mechanics of the iterator protocol. The example is a bit confusing because in the example: rev = Reverse('spam')
iter(rev)
<__main__.Reverse object at 0x00A1DB50>
for char in rev:
... print(char) ... m a p s it behaves as expected, but if you repeat the for statement just afterwards, it does nothing: for char in rev: ... print(char) ...
The problem is in the definition of the __iter__() method, because it does not reset the index. This is the code that appears in the tutorial: class Reverse: """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] and this is my proposal: class Reverse: """Iterator for looping over a sequence backwards.""" def __init__(self, data): self.data = data def __iter__(self): self.index = len(self.data) return self def __next__(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] Note: this is not perfect, because it does not admit nested iterations over the same object (that's the reason why generally iterator objects (different from the original data) are necessary). Regards. Raúl Gonzalo Díaz Automatización Red y Servicios | Soporte de Red Edif. Torras i Bages, c/Cinca, 39-41, Planta 1 | 08030 Barcelona, España (GMT +1) Telf. +34 93 403 06 61 Email raul.gonzalodiaz@telefonica.com<mailto:raul.gonzalodiaz@telefonica.com> [cid:image001.png@01DB18BA.FBCE5A30] ________________________________ Este mensaje y sus adjuntos se dirigen exclusivamente a su destinatario, puede contener información privilegiada o confidencial y es para uso exclusivo de la persona o entidad de destino. Si no es usted. el destinatario indicado, queda notificado de que la lectura, utilización, divulgación y/o copia sin autorización puede estar prohibida en virtud de la legislación vigente. Si ha recibido este mensaje por error, le rogamos que nos lo comunique inmediatamente por esta misma vía y proceda a su destrucción. The information contained in this transmission is confidential and privileged information intended only for the use of the individual or entity named above. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this transmission in error, do not read it. Please immediately reply to the sender that you have received this communication in error and then delete it. Esta mensagem e seus anexos se dirigem exclusivamente ao seu destinatário, pode conter informação privilegiada ou confidencial e é para uso exclusivo da pessoa ou entidade de destino. Se não é vossa senhoria o destinatário indicado, fica notificado de que a leitura, utilização, divulgação e/ou cópia sem autorização pode estar proibida em virtude da legislação vigente. Se recebeu esta mensagem por erro, rogamos-lhe que nos o comunique imediatamente por esta mesma via e proceda a sua destruição

Iterator is onetime. So this is not a bug. Iterable may return an iterator that iterate from the start. Containers including list, tuple, and dict are re-iterable. On the other hand, file object is one shot iterable. 2024年10月7日(月) 21:22 RAUL GONZALO DIAZ <raul.gonzalodiaz@telefonica.com>:

Iterator is onetime. So this is not a bug. Iterable may return an iterator that iterate from the start. Containers including list, tuple, and dict are re-iterable. On the other hand, file object is one shot iterable. 2024年10月7日(月) 21:22 RAUL GONZALO DIAZ <raul.gonzalodiaz@telefonica.com>:
participants (2)
-
Inada Naoki
-
RAUL GONZALO DIAZ