The Iterator pattern hides how a collection is traversed behind a tiny, uniform protocol: give me an iterator, and I will keep asking it for the next value until it says stop. In Python that protocol is two methods. iter returns the iterator, and next hands back one item at a time and raises StopIteration when there are none left.
We start with the simplest possible backend: an in-memory list. Build ListCursor, an iterator that walks a list in order. The scaffolding (an index, iter returning self) is done. Implement next so it returns items one by one and raises StopIteration once the list is exhausted.
This is the whole seed of pagination: a stateful cursor that remembers where it is.
class ListCursor:
def __init__(self, items):
self._items = list(items)
self._index = 0
def __iter__(self):
return self
def __next__(self):
"""Return the next item; raise StopIteration when the list is used up."""
# TODO: hand back whichever item of self._items self._index currently
# points at, and move that index forward so the following call sees the
# one after it. Once the index has reached the end of the list there is
# nothing to return, so signal exhaustion with StopIteration instead.
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
The Iterator pattern hides how a collection is traversed behind a tiny, uniform protocol: give me an iterator, and I will keep asking it for the next value until it says stop. In Python that protocol is two methods. iter returns the iterator, and next hands back one item at a time and raises StopIteration when there are none left.
We start with the simplest possible backend: an in-memory list. Build ListCursor, an iterator that walks a list in order. The scaffolding (an index, iter returning self) is done. Implement next so it returns items one by one and raises StopIteration once the list is exhausted.
This is the whole seed of pagination: a stateful cursor that remembers where it is.
Press Run Tests or ββ© to check your solution.