Complete worked example
python
def collect_pages(fetch_page, max_pages=3):
if type(max_pages) is not int or not 1 <= max_pages <= 5:
raise ValueError("page budget must be 1..5")
cursor, seen, ids = None, set(), []
for _ in range(max_pages):
if cursor in seen:
raise ValueError("cursor cycle")
seen.add(cursor)
page = fetch_page(cursor)
if not isinstance(page, dict) or "next" not in page or not isinstance(page.get("items"), list):
raise ValueError("page shape required")
if any(not isinstance(item, str) or not item for item in page["items"]):
raise ValueError("nonempty identifiers required")
ids.extend(page["items"])
cursor = page["next"]
if cursor is None:
return sorted(set(ids))
if not isinstance(cursor, str) or not cursor:
raise ValueError("cursor must be nonempty text or None")
raise ValueError("page budget exhausted before completion")- Reasoning
- Follow an injected page provider while bounding work and distinguishing a complete collection from a truncated one. Compare the stated values and failure boundary before changing the implementation.