Custom Iterators Implement __iter__ And __next__
A class with __iter__ returning self and __next__ raising StopIteration plugs into for-loops, iter(), and next() like any builtin sequence.
Code
class Cursor:
"""Iterate in-memory pages the way a paged endpoint hands out pages."""
def __init__(self, pages):
self.pages = pages
self.position = 0
def __iter__(self):
# Returning self lets for-loops drive this same object.
return self
def __next__(self):
if self.position >= len(self.pages):
raise StopIteration # Ending the loop is the iterator's job.
page = self.pages[self.position]
self.position += 1
return page
pages = [["user1", "user2"], ["user3"], ["user4", "user5"]]
for page in Cursor(pages):
print("page:", page)
# iter() and next() drive the same protocol by hand.
manual = iter(Cursor(pages))
print("manual:", next(manual), next(manual))
# A fresh Cursor re-reads the same backing list from the start.
second_pass = [row for page in Cursor(pages) for row in page]
print("second pass:", second_pass)Output
Captured from a sandboxed run of this snippet in the build pipeline.
page: ['user1', 'user2']
page: ['user3']
page: ['user4', 'user5']
manual: ['user1', 'user2'] ['user3']
second pass: ['user1', 'user2', 'user3', 'user4', 'user5']How it works
The working surface is the class Cursor and the functions __init__, __iter__ and __next__ — everything else is wiring.
Repetition is confined to for page in Cursor(pages) — the rest of the file is straight-line. The failure path is explicit — StopIteration is raised when the guard condition holds.
Watch out for
- Runs on the standard library alone; nothing to install.
- The guard
self.position >= len(self.pages)short-circuits the flow with an earlyraisewhen its condition holds.
Using it
The main signature reads def __init__(self, pages)
The demo output is labeled (page:, manual:, second pass:), so every printed line maps back to its originating operation.
Key statements
def __init__(self, pages):
self.pages = pages
self.position = 0
def __iter__(self):
# Returning self lets for-loops drive this same object.
return self
def __next__(self):
if self.position >= len(self.pages):
raise StopIteration # Ending the loop is the iterator's job.
page = self.pages[self.position]
self.position += 1
return page
FAQ
- What happens if the preconditions do not hold?
- `StopIteration` is raised at the guard (`self.position >= len(self.pages)`), so invalid state never reaches the main logic.
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `__init__`, `__iter__`, `__next__` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.