Project: a paginated API client
Implement a pagination core that follows opaque page tokens, rejects repeated tokens and enforces a page budget. Use a deterministic adapter fixture first, then connect a separately tested HTTP adapter with bounded destinations and responses.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 40 minutes; optional deep dive: 25 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
- HTTP clients, timeouts and pagination
- Debug failures and make retries safe
- Tests that catch real mistakes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
A real network client needs an approved environment or your own local lab. Browser fixtures do not certify external connectivity.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Translate requirements into contracts
- Implement and test a complete small slice
- Explain production gaps and next increments
Project brief and review
Implement a pagination core that follows opaque page tokens, rejects repeated tokens and enforces a page budget. Use a deterministic adapter fixture first, then connect a separately tested HTTP adapter with bounded destinations and responses. Reading time does not include your independent implementation time.
Requirements
- Inject the page-fetch operation.
- Reject repeated page tokens.
- Enforce a maximum page count.
- Keep network credentials and transport errors outside the pure aggregation.
Acceptance checklist
These self-checks are page-local, not saved or automatically judged.
Further increments
- Implement a local fixture HTTP server for timeout/status/body tests.
- Add authenticated transport without exposing secrets in logs or source.
Build this as a multi-file project: Paginated client / offline fixture transport
Explicitly offline mapping transport only: no HTTP, credentials, framework or live API. Validated pages contain exactly items/next; flat items contain exact positive integer id and string title. None terminates; every string, including empty, is an opaque continuation token. Page count is not an item/byte memory budget. The lesson's single-file browser runner does not import these files.
- Preview and download the starter. In Standalone Playground, sign in and choose Import JSON as a new local project. Importing replaces local editor files only after its existing unsaved-edit confirmation; export your work first.
- Implement copy_page(page) and FixtureTransport in fixture_transport.py. Validate the complete flat schema, excluding bool ids, and own the returned page dict, items list and item dicts. Preserve duplicates and order; fixture data must not be mutated or aliased. The callable records requested tokens and fails on missing fixtures.
- Implement collect(fetch, max_pages=5) in paginator.py. Validate an exact positive integer budget; follow opaque tokens in order, even after an empty continuing page. Reject cycles before fetching again and reject budget exhaustion instead of returning partial success. Transport exceptions propagate unchanged.
- Implement unique_fixture_items((pages, budget)) in transfer.py using complete bounded traversal. Keep the first item per id, not the last or the first title. Validate even later duplicates before ignoring them. Explain why these fixtures do not test network deadlines, status handling or authentication.
- Save snapshot explicitly, then Run current files to execute
main.py's 10 public standard-library tests. The suite stops at the first failure; the untouched starter raises a realNotImplementedError. Inspect the named failing case, edit and rerun. Add an original test and explain why it would catch a tempting wrong approach. - Stop an active program before changing its baseline. Export current project JSON to keep your exact files; import the original starter as a separate local project to reset, with the same edit-loss confirmation. A saved version can be restored explicitly. Record your saved artifact and limitations separately if private project self-review is enabled.
Public tests are visible and editable, not exhaustive grading or proof that you worked without the reference. No completion, reading milestone or judge acceptance is awarded. Run needs the independently enabled approved Python Playground runtime; if unavailable, source editing/export remains available without a fallback. Frameworks, cloud services, live APIs and persistent database sessions remain unsupported. For local work, download all previewed source files into the same empty folder and run python main.py from that folder in your own Python 3.11+ environment. Downloads do not install Python or provide offline server execution.
References are excluded by default. Including them changes only the new download, never your current lesson or saved project.
Project brief and boundaries
A paginator follows page tokens until the provider declares the end. Separate traversal from the operation that obtains each page.
Understand first
An injected fixture lets you test order, termination and budgets without live HTTP, secrets or unreliable remote services.
Words you will see
- Page
- One response containing items and a next marker.
- Opaque token
- A marker to pass back unchanged rather than parse or invent.
- Injected operation
- A supplied callable used by the core instead of a hard-coded external action.
Decompose input and ownership
The core begins with token None and asks fetch(token) for a page. A page contains an ordered items list and next, either another opaque string or None. None terminates; an empty items list does not necessarily terminate. Specify item shape at the adapter boundary.
The sample mapping acts as an offline fetch operation. It owns page fixtures; the consumer must not pop items or overwrite next. A new outer result list does not automatically make nested item dictionaries private. The exercises explicitly copy their supported flat item records.
Build termination before transport
First consume one terminal page. Add two pages and ordered concatenation, then an empty continuation page, repeated-token detection and a page budget. Record fetched tokens in a fixture to verify no extra call occurs after termination or beyond the budget.
Browser-local dictionary lookup is not HTTP. A future adapter owns destination policy, credentials, response size, shape checks and request deadlines. This lesson sends no requests, installs nothing, and makes no claim that timeout or authenticated transport has been tested.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
calls = []Own a fixture log of requested tokens, not network telemetry.
calls.append(token)Record each injected call in the local test fixture.
second = fetch(first["next"])Use the supplied token unchanged even when the first items list is empty.
print(calls)Observe exactly the two modeled page requests.
Implement a pagination core that follows opaque page tokens, rejects repeated tokens and enforces a page budget. Use a deterministic adapter fixture first, then connect a separately tested HTTP adapter with bounded destinations and responses.
Conceptual offline pagination, not a network trace
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- TraversalOwn token history, item order and page budget.
- Injected fetchReturn a deterministic fixture page; real transport stays outside.
- ResultReturn only on declared end; loops and exhausted budgets are failures.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Make the first page terminal.
Try: Set its next value to None, remove the second fetch, and replace the item print with print(first["items"]).
A terminal first page yields no items and requires one call.
Change the opaque marker.
Try: Rename "later" to "cursor:x" in both fixture locations.
The same traversal works without parsing the token.
Before you move on
A page contains no items and next='after'. Should the paginator stop?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. The next marker controls termination. Fetch after within the page budget; an empty intermediate page may still have later data.
Design a testable slice
A page budget and a token-history set prevent different kinds of unbounded traversal. Neither should return a truncated success.
Understand first
A server can repeat a token or produce a long chain of distinct tokens. Both need explicit, testable stopping policies.
Words you will see
- Cycle
- A traversal that returns to an already requested marker.
- Budget
- A maximum number of page fetches allowed.
- Truncation
- Returning only a prefix of requested data.
Order checks before fetch
Before every fetch, check whether its token was already requested and whether the page budget permits another request. Mark the token before calling fetch. This prevents a repeated token from triggering a second external operation even if the previous page had no items.
An end marker reached on the last allowed page succeeds. A nonterminal page at that point fails instead of returning accumulated items. Validate max_pages as an exact positive integer; booleans and zero must not silently behave as ordinary page counts.
Test paths, not only results
Use a fixture call log to assert the exact token sequence on success and failure. A repeated-token regression should show one fetch for each unique requested marker. A budget regression should show no fetch after the allowed count.
The example models a small repeated chain and raises a safe error after two unique tokens. It does not simulate HTTP retry policy. Real retries consume time and request budgets under a separate adapter contract; an offline traversal cannot prove deadlines, status handling or rate-limit compliance.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
seen = set()Own a separate set for traversal history.
if token in seen:Check before the next modeled lookup.
seen.add(token)Remember the token that is about to be consumed.
token = next_tokens[token]Follow the fixture's marker unchanged.
The paginator owns traversal and termination; the adapter owns transport, authentication and response validation. Treat a next token as opaque data. If a provider uses URLs instead, validate the origin and redirects rather than granting arbitrary fetch authority.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Create a longer cycle.
Try: Use {None: "b", "b": "c", "c": "b"} and a four-iteration range.
The cycle is rejected after three unique markers.
Shorten the observation window.
Try: Change range(3) to range(2).
No cycle diagnostic prints yet; a real paginator must then raise budget exhaustion, not return success.
Before you move on
A budget of two permits page one to point to page two, and page two ends. Is that a budget error?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Termination on the second allowed page is success. Only needing a third fetch exceeds that budget.
A bounded pagination core
The preserved pagination core returns only after a declared end marker. It delegates page retrieval but owns traversal.
Understand first
You can verify loop detection, ordering and budget behavior without embedding credentials or transport logic in the collector.
Words you will see
- Callable
- A value that can be invoked, such as a function or bound method.
- extend
- A list operation appending each item from another iterable.
- Terminal page
- A page whose next marker is None.
Read the original loop
collect owns a token, seen set and result list. Every iteration rejects a repeated token before fetching, adds its items in order, and reads next. The supplied bound dictionary lookup is the fetch callable. The two pages contribute 1, 2 and then 3.
The loop returns only when next is None. If all allowed iterations finish with a continuation, it raises Page budget exceeded. It makes no transport calls other than the injected function and never tries to decode or increment a token.
Explain the exact ownership and limits
extend makes a new outer list but shares references to mutable items inside pages. This reference uses integers, so that sharing cannot be observed by mutating an integer. The guided shape-specific copy increment strengthens ownership for flat dictionary items; it does not retroactively make this reference a deep copier.
The reference assumes a valid page shape and does not validate the budget type. Independent work needs explicit validation and adapter contract tests. With p fetched pages and m total items, traversal uses O(p + m) state and expected linear work under bounded-size tokens; returning all items is not streaming constant memory.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
token, seen, result = None, set(), []Start a new traversal with private state.
if token in seen:Reject a token cycle before fetching again.
result.extend(page['items'])Append in page order, sharing mutable item references if present.
if token is None:Only this declared terminal marker allows success.
The injected mapping adapter makes page traversal deterministic. The core returns only after a declared end token; budget exhaustion and loops remain explicit failures.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Use an empty final page.
Try: Replace the final items [3] with [].
The result becomes [1, 2] and still terminates successfully.
Exercise repeated-token failure.
Try: Change the final next marker from None to 'b'.
The next iteration rejects b rather than fetching it twice.
Before you move on
What happens with max_pages=1 and the supplied two-page fixture?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
The first page is fetched but is nonterminal. The function raises Page budget exceeded instead of returning [1, 2].
Define paginator and transport responsibilities
The pagination core receives an injected fetch operation that maps an opaque token to a validated page containing items and next. It owns traversal order, repeated-token detection, and the page budget. The HTTP adapter owns destination policy, credentials, response status, body limits, and schema validation. Keep transport-specific exceptions distinct from traversal failures. A page contract must specify which value terminates traversal and whether an empty items list can still carry a continuation.
The offline mapping fixture serves two pages: the initial token yields 1 and 2, and token b yields 3 and completion. collect returns 1, 2, 3 in page order. It retains all collected items, so a page-count bound alone does not bound result bytes when one page is huge. The fixture demonstrates deterministic traversal, not external networking, provider authentication, real timeout behavior, or correctness of arbitrary response envelopes.
Implement numbered progress and termination checks
1. Define and test one completed page. 2. Add two-page traversal with ordered accumulation. 3. Track requested tokens and reject loops. 4. Enforce a page limit that raises rather than returns a truncated normal result. 5. Validate page envelopes at the adapter boundary. 6. Add a real HTTP adapter behind the same contract and test it separately against a controlled local fixture server.
The initial None token is recorded before the first fetch, while a returned None ends traversal immediately. Tokens used in the seen set need a documented hashable representation; arbitrary decoded objects are not automatically valid opaque tokens. Validate the page budget as a positive integer in an independent implementation. Do not terminate solely on an empty page unless the provider contract says so, and do not replace returned tokens with locally guessed page numbers.
Specify adversarial unit and transport acceptance
Paginator tests cover one page, two pages, an empty terminating page, an empty continuing page, an immediate repeated token, a longer token cycle, and budget exhaustion. Count adapter calls to prove the client does not fetch again after detecting a cycle. Assert that budget exhaustion raises even if some items were already collected. Include invalid page shape at the adapter boundary and an injected fetch exception that must remain distinguishable from a completed empty collection.
Transport integration tests should cover delayed response, connection failure, unexpected status, malformed JSON, body-size overflow, redirect policy, and cleanup after rejection. Use a server you control rather than an uncontrolled public endpoint. If pagination returns URLs instead of tokens, validate every resolved destination and redirect against the allowed origin policy. Never attach credentials to an unapproved host simply because a remote page supplied a link, and redact sensitive response context from diagnostics.
Design bounded recovery and independent work stages
Set a total operation deadline alongside per-request limits and bounded retry backoff. Classify retryable reads according to the provider contract; a permanent schema failure normally needs repair, not another attempt. Decide whether callers require a full collection or can consume a stream of items with explicit incomplete-traversal signaling. Streaming reduces retained items but transfers partial-consumption and cleanup responsibilities to the caller, so it is an API change rather than a transparent optimization.
Budget one focused session for traversal and adversarial unit tests, then separate sessions for transport integration and retry or cancellation policy. Record which acceptance cases actually ran and which provider-specific assumptions remain unverified. Close responses and client resources in all paths. The executable reference is only the injected traversal slice; it does not prove real network access, connection pooling, authenticated provider success, or operational readiness of a deployed integration.
Transfer question: The caller wants items as they arrive instead of waiting for a full list. What changes beyond replacing result.extend with yielding?
Define what happens when traversal fails after some items have already been observed: the stream must raise or provide an explicit incomplete status, and callers must not label partial data complete. Keep token-cycle, page, item, byte, and deadline limits. Establish who closes a partially consumed stream and its active response resources. Test early consumer exit, failure on a later page, and cancellation while fetching. A stream lowers retained-result memory but does not remove adapter buffers or provider limits. Callers needing an atomic complete report should stage results separately and publish only after successful exhaustion.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Build before opening the reference
Inject the page-fetch operation. Reject repeated page tokens. Enforce a maximum page count. Keep network credentials and transport errors outside the pure aggregation. Demonstrate the acceptance cases and document any unsupported requirement.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Validate and own one fixture page
Guided increment 1: validate a deliberately small page schema and copy its supported mutable containers.
The contract
- page must be a dict with exactly items and next. items is a list; next is None or an exact str, including empty string as an opaque token.
- Each item is a dict with exactly id and title: id exact positive int excluding bool, title exact str including empty. Any invalid shape or value raises ValueError.
- Return a fresh page dict, items list and item dicts. Duplicates and order remain. Scalar strings/ints need no deep copy; nested item payloads are unsupported.
- Run this deterministic increment in browser Python with no external I/O. It is not a completed deployment or full independent project.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Copied nonempty page
import copy supplied = {"items":[{"id":1,"title":"a"}],"next":"x"} before = copy.deepcopy(supplied) result = copy_page(supplied) expected = {"items":[{"id":1,"title":"a"}],"next":"x"} assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" assert result is not supplied and result["items"] is not supplied["items"], "Output must be owned" result["items"][0]["title"] = "edited" assert supplied == before, "Caller input changed through result alias" - Empty terminal page
import copy supplied = {"items":[],"next":None} before = copy.deepcopy(supplied) result = copy_page(supplied) expected = {"items":[],"next":None} assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" assert result["items"] is not supplied["items"], "Output list must be owned" - Duplicate items and empty token
import copy supplied = {"items":[{"id":2,"title":""},{"id":2,"title":""}],"next":""} before = copy.deepcopy(supplied) result = copy_page(supplied) expected = {"items":[{"id":2,"title":""},{"id":2,"title":""}],"next":""} assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Boolean identity fails
import copy supplied = {"items":[{"id":True,"title":"a"}],"next":None} before = copy.deepcopy(supplied) try: result = copy_page(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Missing next
import copy supplied = {"items":[]} before = copy.deepcopy(supplied) try: result = copy_page(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Unsupported nested payload
import copy supplied = {"items":[{"id":1,"title":"a","tags":[]}],"next":None} before = copy.deepcopy(supplied) try: result = copy_page(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
How does validate and own one fixture page support an independent project, and what remains untested?
Shape validation and flat copying take O(m) time and storage for m items. Ownership is complete for this flat schema, not arbitrary nested records. No transport exists in this increment.
Collect bounded offline pages
Guided increment 2: implement traversal against an offline page mapping. This mapping models an adapter and does not send HTTP.
The contract
- spec is (pages, budget); pages maps None/string tokens to copy_page-compatible pages. budget is exact positive int.
- Start at None, preserve page/item order and duplicates, stop only at next=None. Empty continuation pages still advance.
- Raise ValueError for missing pages, repeated tokens, invalid pages or exhausted budget. Return only complete results with copied flat items; never mutate fixture pages.
- Run this deterministic increment in browser Python with no external I/O. It is not a completed deployment or full independent project.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Two ordered owned pages
import copy supplied = ({None:{"items":[{"id":2,"title":"b"}],"next":"x"},"x":{"items":[{"id":1,"title":"a"}],"next":None}},2) before = copy.deepcopy(supplied) result = fixture_items(supplied) expected = [{"id":2,"title":"b"},{"id":1,"title":"a"}] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" result[0]["title"] = "edited" assert supplied == before, "Caller input changed through result alias" - Empty terminal
import copy supplied = ({None:{"items":[],"next":None}},1) before = copy.deepcopy(supplied) result = fixture_items(supplied) expected = [] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Empty page continues with duplicate
import copy supplied = ({None:{"items":[],"next":""},"":{"items":[{"id":1,"title":"a"},{"id":1,"title":"a"}],"next":None}},2) before = copy.deepcopy(supplied) result = fixture_items(supplied) expected = [{"id":1,"title":"a"},{"id":1,"title":"a"}] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Repeated token
import copy supplied = ({None:{"items":[],"next":"x"},"x":{"items":[],"next":"x"}},3) before = copy.deepcopy(supplied) try: result = fixture_items(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Nonterminal last budget page
import copy supplied = ({None:{"items":[{"id":1,"title":"a"}],"next":"x"}},1) before = copy.deepcopy(supplied) try: result = fixture_items(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Invalid boolean budget
import copy supplied = ({None:{"items":[],"next":None}},True) before = copy.deepcopy(supplied) try: result = fixture_items(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
How does collect bounded offline pages support an independent project, and what remains untested?
The fixture mapping stands in for injected fetch, preserving the division between traversal and transport. For p pages and m items this solution retains O(p+m) state and expected linear work. It does not test HTTP or installed clients.
Keep first item identities
Transfer: collect with the same failure and ownership rules, then keep the first record for each id in traversal order.
The contract
- Use the same pages/budget input and copy_page shape rules as fixture_items, validating all fetched items including duplicates.
- Return a fresh list of copied flat item dicts, first occurrence per id winning even if a later title differs. Do not sort or deduplicate by title.
- Retain cycle/budget/missing-page failures and no partial success. Never mutate fixtures or share mutable item dicts with them.
- Run this deterministic increment in browser Python with no external I/O. It is not a completed deployment or full independent project.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- First winner across pages
import copy supplied = ({None:{"items":[{"id":2,"title":"old"}],"next":"x"},"x":{"items":[{"id":2,"title":"new"},{"id":1,"title":"old"}],"next":None}},2) before = copy.deepcopy(supplied) result = unique_fixture_items(supplied) expected = [{"id":2,"title":"old"},{"id":1,"title":"old"}] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" result[0]["title"] = "edited" assert supplied == before, "Caller input changed through result alias" - Empty unique result
import copy supplied = ({None:{"items":[],"next":None}},1) before = copy.deepcopy(supplied) result = unique_fixture_items(supplied) expected = [] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Same title different identities
import copy supplied = ({None:{"items":[{"id":3,"title":"a"},{"id":1,"title":"a"}],"next":None}},1) before = copy.deepcopy(supplied) result = unique_fixture_items(supplied) expected = [{"id":3,"title":"a"},{"id":1,"title":"a"}] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Validate duplicate before ignoring
import copy supplied = ({None:{"items":[{"id":1,"title":"a"},{"id":1,"title":3}],"next":None}},1) before = copy.deepcopy(supplied) try: result = unique_fixture_items(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Budget remains enforced
import copy supplied = ({None:{"items":[],"next":"x"}},1) before = copy.deepcopy(supplied) try: result = unique_fixture_items(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Missing fixture remains error
import copy supplied = ({},2) before = copy.deepcopy(supplied) try: result = unique_fixture_items(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
How does keep first item identities support an independent project, and what remains untested?
The new winner policy changes semantics while traversal validation stays intact. The implementation retains the full collected list plus O(u) deduplication state for u unique ids, not constant memory. A real adapter and independent whole-project implementation remain future work.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneProduction hardening is separate
Transport is a separately owned boundary. Offline pagination tests cannot establish real HTTP reliability or security.
Understand first
Timeouts, response sizes, status codes and credentials are properties of the actual adapter, not of dictionary lookup.
Words you will see
- Transport
- The mechanism exchanging a request and response.
- Deadline
- The latest allowed completion time for an operation.
- Retry classification
- Deciding which failures may safely be attempted again.
Design an adapter contract honestly
The adapter should return a validated page or raise a documented error. It owns connection/request deadlines, allowed destinations, redirect policy, response-size limits and safe credential handling. If tokens are URLs, do not treat them as authority to fetch arbitrary origins.
Distinguish a missing page fixture from transport timeout and malformed response. The sample models a transport failure with an injected function and shows propagation. It performs no HTTP and cannot establish how a real client handles sockets, redirects or a provider's rate limits.
Keep partial success out of errors
The core should not turn an adapter error into an empty terminal page; that would silently truncate data. Preserve failure so the caller can decide whether to retry a whole operation or expose an explicit partial mode with a new contract.
Plan local adapter tests with controlled responses for timeouts, statuses and oversized bodies when that adapter is built. No secrets, package installation, system processes or live HTTP are needed for these browser-local increments. Do not attach deployment claims to an offline exception fixture.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
def fixture_fetch(token):Supply a deterministic error-producing adapter.
raise TimeoutError("fixture deadline")Model a failure without waiting or touching a network.
return fetch(None)Let the failure propagate through the core boundary.
print("No complete report")Report failure rather than a fabricated empty success.
A real HTTP client needs connection/request deadlines, response-size limits, retry classification and provider-specific rate policy. This reference deliberately uses an offline adapter and is not a claim that external network requests were executed.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Model a different expected error.
Try: Replace TimeoutError with ValueError in both raise and except.
The error path still reports no complete report; the category has changed.
Model one valid page.
Try: Return {"items": [], "next": None} instead of raising, and print the first_page result.
The terminal page is displayed; this is a fixture success, not network evidence.
Before you move on
If the second adapter call fails, may the collector return the first page as a successful complete report?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Completeness has not been established. Propagate the error unless the API explicitly defines a separately labeled partial-result mode.
Review and transfer
Deduplicating paginated records is a changed contract: decide the identity key, winner policy and output ownership explicitly.
Understand first
Repeated items can occur across pages. A set of whole records is not a substitute for deciding which record survives.
Words you will see
- Stable deduplication
- Keeping the first occurrence of each identity in traversal order.
- Identity key
- A field used to decide whether two records represent the same item.
- Copy depth
- How far ownership separation extends into nested data.
Choose the transfer rule
The transfer keeps the first record for each exact positive integer id and retains traversal order. Later duplicates with different titles do not replace the first. Flat records contain only id and title, so copying each dictionary separates all mutable supported containers.
Do not sort ids or deduplicate by title; different ids may share a title. Validate even a later duplicate before ignoring it, so invalid input cannot hide behind an earlier record. Budget and cycle behavior remain unchanged from ordinary pagination.
Test ownership as well as selection
The sample copies selected flat dictionaries. After collection, changing a result title does not alter page fixtures. A shallow dict copy would not isolate nested tags if those were later added; either reject nested shape or define a deeper copying contract.
Expected deduplication work is linear in item occurrences under ordinary bounded-id hashing, with a seen-id set and output growing by unique ids. Implement this transfer independently. Browser fixtures do not test provider overlap guarantees or consistency while a remote dataset changes.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
seen = set()Track accepted identity keys separately from output records.
if item["id"] not in seen:Keep the first occurrence of each id.
result.append(dict(item))Copy each supported flat record rather than sharing its dictionary.
result[0]["title"] = "edited"Probe result ownership without changing the source record.
After implementation, explain the boundary cases and change one requirement without rewriting unrelated behaviour. Implement a local fixture HTTP server for timeout/status/body tests. Add authenticated transport without exposing secrets in logs or source. Keep a record of what you tested; a viewed reference is not proof you independently completed the project.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Use a new second id.
Try: Change the second record id from 2 to 3.
All three records survive in traversal order.
Expose shared ownership.
Try: Replace dict(item) with item.
Editing the result changes items[0], so the final print becomes edited.
Before you move on
Two pages contain id 4 with titles old then new. Which title survives this transfer, and where does id 4 appear?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
old survives at its first traversal position. Later duplicates are validated but do not replace or move the first item.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.