Python Iterators
What Is an Iterator?
An iterator is an object that represents a stream of data. It implements the iterator protocol, which consists of two methods: __iter__()
and __next__()
.
- The
__iter__()
method returns the iterator object itself. - The
__next__()
method returns the next item from the stream. If there are no more items, it should raise aStopIteration
exception.
Iterators are fundamental to how for
loops and other iteration constructs work in Python.
The collections.abc.Iterator
abstract base class (ABC) defines this minimal interface for iterator types.
The iter and next Methods
To be recognized as an iterator, a class must implement both the __iter__()
and __next__()
methods:
from collections.abc import Iterator
class MyIterator(Iterator):
def __init__(self, data):
self.data = data
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index < len(self.data):
value = self.data[self.index]
self.index += 1
return value
else:
raise StopIteration
# Example usage:
my_list = [10, 20, 30]
my_iter = MyIterator(my_list)
for item in my_iter:
print(item) # 10, 20, 30
# You can also manually iterate:
my_iter_manual = MyIterator(my_list)
print(next(my_iter_manual)) # 10
print(next(my_iter_manual)) # 20
Using collections.abc.Iterator
You can check if a class or object is an iterator using isinstance
or issubclass
:
from collections.abc import Iterator
class AnotherIterator(Iterator):
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__ (self):
if self.current < self.end:
value = self.current
self.current += 1
return value
else:
raise StopIteration
print(issubclass(AnotherIterator, Iterator)) # True
print(isinstance(AnotherIterator(0, 5), Iterator)) # True
# Built-in iterators also conform:
list_iterator = iter([1, 2, 3])
print(isinstance(list_iterator, Iterator)) # True
It's generally recommended to inherit directly from collections.abc.Iterator
(or other relevant ABCs) when designing your classes. This makes your code more explicit about its intended interface and can help static analysis tools. However, it's not strictly mandatory; Python's duck typing means that if your class implements the required __iter__()
and __next__()
methods, it will be recognized as an iterator, even without explicit inheritance from the ABC.
Key Takeaways
- Iterators are objects that produce data one item at a time.
- They must implement both
__iter__()
(returningself
) and__next__()
(returning the next item or raisingStopIteration
). - The
collections.abc.Iterator
ABC provides a standard way to check for this protocol compliance.