Iterator vs Iterable vs Generator
suggest changeAn iterable is an object that can return an iterator. Any object with an __iter__ method that returns an iterator is an iterable. It does not have to carry extra state. An object without __iter__ can still be iterable if it implements __getitem__. That method takes indices starting from zero and raises an IndexError when the indices are no longer valid.
Python’s str class implements __getitem__, and it also implements __iter__.
An iterator is an object that produces the next value in a sequence when you call next() on it. An iterator implements __iter__ (usually returning itself) and __next__. An object with only __next__ is not enough for a for loop, which needs __iter__. An iterator raises StopIteration after it is exhausted and cannot be re-used at this point.
Iterable classes:
An iterator class defines __iter__ and __next__. The example returns self from __iter__, so it is an iterator, not only an iterable. The method bodies are stubs (condition and item are undefined), so the classes do not run as written:
class MyIterable:
def __iter__(self):
return self
def __next__(self):
#code
#Classic iterable object in older versions of python, __getitem__ is still supported...
class MySequence:
def __getitem__(self, index):
if (condition):
raise IndexError
return (item)
#Can produce a plain `iterator` instance by using iter(MySequence())
collections.Iterator was removed from collections. Instantiating the abstract class looks like this:
import collections.abc
collections.abc.Iterator()
# TypeError: Can't instantiate abstract class Iterator without an implementation for abstract method '__next__'
The old prompts (>>> TypeError: Cant instantiate abstract class Iterator with abstract methods next and the __next__ variant) are not what this interpreter raises. collections.Iterator() raises AttributeError: module 'collections' has no attribute 'Iterator'.
class MyIterable(object): # or collections.abc.Iterator
....
def __iter__(self):
return self
def next(self): #code
__next__ = next
The next function and the __next__ = next line above are not indented into the class, so they do not become MyIterable.__next__. That break is left as written.
ex1 = MyIterableClass()
ex2 = MySequence()
for (item) in (ex1): #code
for (item) in (ex2): #code
MyIterableClass is not defined; the class above is MyIterable. The loop bodies are stubs, so these lines do not run.
Generators are simple ways to create iterators. A generator is an iterator and an iterator is an iterable.