Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 51 / BUILDING AND SHIPPING

HTTP clients, timeouts and pagination

Treat remote responses as fallible, bounded external input.

IntermediateTutorial 14 min core+12 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners who can read small Python functions and want to apply the listed foundations.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

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.

Outbound HTTP is disabled in browser Python. Network examples need a local environment; mocked/model responses are not live service responses.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Explain define a remote contract
  • Apply pagination needs termination
  • Reason about safe retries and destinations
01

Define a remote contract

A response is external input, not a trusted result. Check status, content type, size and shape before treating its contents as useful data.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A successful connection can deliver an error page or an oversized body. Validating separate boundaries keeps transport success from becoming false application success.

Words you will see

Status
The response code describing the server's HTTP outcome.
Content type
A declaration of the body's representation, such as JSON.
Envelope
An outer response structure containing data and continuation metadata.

Check the fixture in stages

The dictionary stands for a controlled response, not an HTTP request. Its status is 200, its content type is application/json and its body is bounded bytes. Only after these checks does decoding produce a dictionary containing items.

A real adapter must enforce a body bound while reading, not only after allocating an unlimited body. A JSON decoder checks syntax, not the business schema. Validate required fields, item types and absent values according to the provider contract.

Keep authority and budgets explicit

A host lab needs an approved destination, client timeout, total operation deadline, accepted statuses and response cleanup. A per-request timeout is not automatically a bound on a multi-page operation. Never place permanent tokens in query strings or diagnostics.

This lesson uses only in-memory fixtures, so it establishes no DNS, TLS, timeout or provider availability evidence. Browser networking has additional restrictions and must not silently bypass them. Preserve real unsupported errors rather than fabricating successful HTTP output.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. import json

    Use the standard decoder, not eval.

  2. if response["status"] != 200 or response["type"] != "application/json":

    Reject a status or representation outside this fixture's contract.

  3. if len(response["body"]) > 80:

    Bound this already-in-memory fixture; real transport must bound reading too.

  4. print(page["items"])

    Display the decoded field after the stated preliminary checks.

Choose allowed schemes/hosts, authentication, timeouts, response size and accepted status/content types. A successful TCP connection does not mean a successful business operation. Do not place permanent tokens in query strings or diagnostic output.

Conceptual response validation pipeline

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. Transport policyApproved destination and bounded operation in a host lab.
  2. RepresentationAccepted status, content type and body size.
  3. DataDecode JSON, then check schema and domain rules.
Predict before you run

Does this example contact a server?

Validate a response fixture before decodingPYTHON 3

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.

Change the status.

Try: Set status to 503.

Validation raises ValueError before decoding the body.

Lower the byte bound.

Try: Change 80 to 5.

The fixture body is rejected as too large rather than partially decoded.

Before you move on

A response is status 200 but contains an HTML error page. May a JSON client accept it as a valid item page?

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. Status alone is insufficient. Enforce representation, decoding and schema requirements and report the failed boundary.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Pagination needs termination

Pagination splits one logical result across responses. Completion follows the provider's continuation contract, not whether one page happens to be empty.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A client can otherwise stop too soon or loop forever. Track requested tokens and enforce a page budget as independent protections.

Words you will see

Continuation token
An opaque value naming the next provider-defined page.
Loop detection
Remembering tokens already requested so a repeated one is rejected.
Page budget
A maximum number of pages allowed for one operation.

Follow continuation, not page length

The first fixture page has no items but points to second. The loop appends nothing from first and still follows its token. Second supplies 7 and next=None, which ends the operation. Empty data is not automatically completion.

The seen set rejects repeated tokens before another fetch. The independent budget rejects an ever-growing chain of fresh tokens. Neither should return a partial list labeled complete when the operation cannot finish.

Tokens do not grant destination authority

These tokens are keys in a local dictionary, not URLs. In a real client a next URL must be resolved and checked against approved destinations, including redirects. External data is not permission to probe internal services.

The fixture bounds page count and contains finite items. Production clients also need total item and body limits, response cleanup and a total deadline. Browser execution cannot establish those host transport behaviors; a controlled server lab is a separate test.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. token = "first"

    Begin with the declared initial token.

  2. if token in seen or len(seen) >= 3:

    Reject cycles and a separate page-budget violation.

  3. items.extend(page["items"])

    Append zero or more items without deciding completion by length.

  4. token = page["next"]

    Only the continuation value determines whether another page is required.

Follow a documented next-page token or link, detect repeated tokens and bound pages/items. Relative links must be resolved against an approved origin; a service-provided next URL is not automatically permission to access an internal address.

Predict before you run

What items are collected?

Continue after an empty pagePYTHON 3

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 cycle.

Try: Set second next to "first".

The repeated-token check raises ValueError.

Tighten the budget.

Try: Change the bound from 3 to 1.

The second page is refused; partial data is not reported as a successful complete result.

Before you move on

Three distinct tokens lead to a fourth, with no cycle. Does cycle detection alone guarantee termination?

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. An endless chain can avoid repeats. Enforce a page limit and a total deadline, and report incomplete traversal when either is exhausted.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Validate a page envelope offline

Decoding JSON and validating a page envelope are separate steps. A syntactically valid value can still have the wrong outer type or items field.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

The original offline reader validates just enough structure to return an items list and optional next value. Its limits should guide further checks, not be hidden.

Words you will see

JSON
A text data format with objects, arrays, strings, numbers, booleans and null.
Schema
The expected field names, types and allowed values.
null / None
JSON's absent-value marker becomes Python None when decoded.

Read the original envelope reader

json.loads converts the fixed text into a Python dictionary. The guard requires a dictionary whose items field is a list. Failure raises ValueError instead of pretending there are no results. The supplied items are [1, 2] and next becomes None.

The function returns a two-part tuple. page.get('next') makes a missing next equivalent to None in this limited contract. It does not validate item fields, a non-null token, status, content type or body size.

Extend the contract deliberately

If a provider requires a next field, replace optional access with a presence check. If items must be IDs, validate each ID and decide whether booleans count as integers. Treat malformed JSON and schema failure as data errors, not automatic retry candidates.

All input here is a local string; no real HTTP is performed. A host adapter must add transport policy, bounded reads, deadlines and cleanup. Unsupported browser network features should produce honest errors, not substitute this fixture's expected output.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. page = json.loads(text)

    Decode text before checking the resulting Python structure.

  2. if not isinstance(page, dict) or not isinstance(page.get('items'), list):

    Reject the wrong outer shape or items type.

  3. return page['items'], page.get('next')

    Return the list and an optional continuation without deeper validation.

  4. print(items, next_token)

    Display the two decoded items and None.

This offline fixture validates a response shape; it does not perform an HTTP request or claim that a provider is reachable.

Predict before you run

What does JSON null become?

Validate a page envelope offlinePYTHON 3

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.

Break the shape.

Try: Replace "items":[1,2] with "items":3 in the input text.

The guard raises ValueError rather than returning a number as a list.

Omit continuation.

Try: Remove the next field from the JSON object.

The existing optional get returns None; a stricter provider contract would need another check.

Before you move on

Does the original reader reject a page whose next is the integer 42?

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. It validates items as a list but does not constrain next. Add token validation if the provider contract requires text or None.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Define remote authority and resource budgets first

A remote client crosses several boundaries before it can return useful data: destination selection, connection, response status, body transfer, decoding, schema validation, and domain validation. Write down allowed schemes and hosts, credential scope, timeout policy, response-size limits, and accepted content types. A successful connection only establishes transport progress. An HTML error page with a successful-looking body read is not a valid JSON page, and syntactically valid JSON can still violate the expected contract.

Budget the entire operation as well as its individual stages. A per-request timeout repeated across many pages can exceed the user's total deadline by a large factor. Account for connection establishment, reading, backoff, and pagination when choosing limits. Close responses and client resources even when validation fails. Avoid assuming that a timeout automatically interrupts every underlying activity; the chosen client library's cancellation and connection-reuse behavior must be understood and tested.

Interpret the offline envelope example precisely

read_page decodes text and requires a dictionary whose items field is a list. For the supplied envelope, it returns the two items and None as the next token. This proves only that local decoding and the stated shape checks work for that input. It does not validate item fields, constrain a non-null token, check status or content type, enforce body size, or demonstrate that any external provider is reachable.

Expand validation according to the actual provider contract, not guesses about familiar APIs. Decide whether a missing next field means completion or malformed data, whether tokens must be strings, and which item identifiers are required. Reject oversized bodies before fully decoding when possible. Keep transport errors distinguishable from schema failures so retry policy does not repeatedly download the same permanently invalid response while hiding the information needed to repair the integration.

Make pagination terminate without granting new authority

Treat continuation tokens as opaque values and track those already requested. Bound page count, total items, and retained result bytes in addition to loop detection. An empty page may still carry a continuation token, so stopping merely because items is empty can truncate results. Conversely, reaching a page budget is an incomplete operation, not permission to return accumulated items as though the provider declared a complete result.

If pagination uses URLs, resolve relative links against an approved base and validate every destination and redirect according to policy. A response field does not confer authority to fetch arbitrary internal addresses or attach credentials to another origin. Prefer a fixed-origin adapter that accepts tokens when the protocol supports it. Record safe diagnostics such as page number and error category rather than complete URLs containing secrets or raw response payloads containing personal information.

Test recovery against a controlled boundary

Use a local fixture server for status handling, malformed JSON, delayed responses, repeated tokens, unexpected redirects, and oversized bodies. Coordinate delays and cancellation deliberately instead of depending on public network availability. An injected fetch function is valuable for deterministic paginator tests, but a separate transport test must verify that the real adapter applies timeouts and closes resources. Keep fixture traffic confined to the intended controlled test environment.

Retry only eligible failures within a bounded attempt and deadline budget. Reads may be retryable under the provider's rules; writes with lost responses can have uncertain committed outcomes. Respect a documented rate policy and validate Retry-After values rather than sleeping without limit. A malformed envelope normally needs correction, not repetition. Surface exhausted retries with the original causal context and avoid converting partial traversal into a normal complete collection.

Transfer question: Page two is empty but contains a new token; page three repeats that token. What should the client report and why?

Continue after the empty page if the provider contract treats its token as valid continuation. Before fetching a token already used, fail with a pagination-cycle error. Do not return pages accumulated so far as a complete report, because neither emptiness nor cycle detection establishes completion. Preserve a safe page count and error classification for diagnosis. Test this sequence with an injected adapter, then independently verify transport bounds using a local fixture server. A caller that explicitly supports partial results may receive a separately labeled incomplete result, but that is a different contract from a successful complete collection.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

Is any next URL returned by a service safe to fetch?
TRANSFER THE IDEA

Rebuild: Validate a page envelope offline

Without copying the worked code, reproduce its observable contract: This offline fixture validates a response shape; it does not perform an HTTP request or claim that a provider is reachable. Then change one boundary input and explain the result.

Your practice starterPYTHON 3

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.

MAKE THE RULE WORK ON NEW INPUTS

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.

Return a value, do not only print itPYTHON 3

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

Guided: validate a stricter page envelope

Decode a bounded JSON string into an items list and continuation. Unlike the original reader, constrain the continuation type.

The contract

  • Input is JSON text of at most 200 characters. Require an object with an items list; next may be absent, None or a nonempty string.
  • Return (items, next) as a tuple; retain item order and duplicates. Invalid JSON, shape, continuation or size raises ValueError.
  • Input text is immutable. Return a newly decoded list. This does not fetch HTTP or validate arbitrary item schemas.
Guided: validate a stricter page envelopePYTHON 3

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.

  1. normal envelope
    import copy
    
    source = '{"items":[1,2],"next":"p2"}'
    before = copy.deepcopy(source)
    result = page_envelope(source)
    assert type(result) is tuple, "Wrong result type"
    expected = ([1, 2], "p2")
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    assert type(result[0]) is list and type(result[1]) is str
  2. empty page can continue
    import copy
    
    source = '{"items":[],"next":"p2"}'
    before = copy.deepcopy(source)
    result = page_envelope(source)
    assert type(result) is tuple, "Wrong result type"
    expected = ([], "p2")
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    
  3. duplicates are data
    import copy
    
    source = '{"items":[3,3],"next":null}'
    before = copy.deepcopy(source)
    result = page_envelope(source)
    assert type(result) is tuple, "Wrong result type"
    expected = ([3, 3], None)
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    
  4. absent optional continuation
    import copy
    
    source = '{"items":[]}'
    before = copy.deepcopy(source)
    result = page_envelope(source)
    assert type(result) is tuple, "Wrong result type"
    expected = ([], None)
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    assert type(result[0]) is list
  5. invalid structures rejected
    import copy
    
    source = '{"items":[0]}'
    before = copy.deepcopy(source)
    result = page_envelope(source)
    assert type(result) is tuple, "Wrong result type"
    expected = ([0], None)
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    for bad in ['{"items":1}', '[]', '{"items":[],"next":42}', '{"items":[],"next":""}', "{", " " * 201]:
        caught = False
        try:
            page_envelope(bad)
        except ValueError:
            caught = True
        assert caught, "Invalid page accepted"
  6. decoded result is independent
    import copy
    
    source = '{"items":[4]}'
    before = copy.deepcopy(source)
    result = page_envelope(source)
    assert type(result) is tuple, "Wrong result type"
    expected = ([4], None)
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    result[0].append(9)
    assert page_envelope(source) == ([4], None)
    assert source == before
    Is the 200-character limit an HTTP read bound?

    No. It bounds already supplied text, not bytes during transfer. Decoding uses O(b) work and storage for b characters and decoded structure; a real adapter needs a byte bound before unlimited reading.

    GUIDED PRACTICE

    Guided: follow bounded fixture pages

    Collect all items from a token-keyed fixture, continuing across empty pages.

    The contract

    • Input maps tokens to {'items': list, 'next': token or None}; start is 'first'. Schema and token existence are trusted here.
    • Return a fresh list preserving page order and all duplicates. At most four pages may be read; repeated tokens or a fifth page raise ValueError.
    • Do not mutate pages or their lists. Tokens are local keys, never URLs, and no network request occurs.
    Guided: follow bounded fixture pagesPYTHON 3

    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.

    1. two pages
      import copy
      
      source = {"first":{"items":[1],"next":"p2"},"p2":{"items":[2],"next":None}}
      before = copy.deepcopy(source)
      result = collect_pages(source)
      assert type(result) is list, "Wrong result type"
      expected = [1, 2]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      
    2. empty completed page
      import copy
      
      source = {"first":{"items":[],"next":None}}
      before = copy.deepcopy(source)
      result = collect_pages(source)
      assert type(result) is list, "Wrong result type"
      expected = []
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      
    3. repeated items preserved
      import copy
      
      source = {"first":{"items":[2,2],"next":None}}
      before = copy.deepcopy(source)
      result = collect_pages(source)
      assert type(result) is list, "Wrong result type"
      expected = [2, 2]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      
    4. empty page with continuation
      import copy
      
      source = {"first":{"items":[],"next":"p2"},"p2":{"items":[8],"next":None}}
      before = copy.deepcopy(source)
      result = collect_pages(source)
      assert type(result) is list, "Wrong result type"
      expected = [8]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      
    5. four page boundary and failures
      import copy
      
      source = {key: {"items":[index], "next": (["p2","p3","p4",None][index])} for index, key in enumerate(["first","p2","p3","p4"])}
      before = copy.deepcopy(source)
      result = collect_pages(source)
      assert type(result) is list, "Wrong result type"
      expected = [0, 1, 2, 3]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      for bad in [{"first":{"items":[],"next":"first"}}, {key: {"items":[], "next": (["p2","p3","p4","p5",None][index])} for index, key in enumerate(["first","p2","p3","p4","p5"])}]:
          snapshot = copy.deepcopy(bad)
          caught = False
          try:
              collect_pages(bad)
          except ValueError:
              caught = True
          assert caught and bad == snapshot
    6. output does not own fixture list
      import copy
      
      source = {"first":{"items":[9],"next":None}}
      before = copy.deepcopy(source)
      result = collect_pages(source)
      assert type(result) is list, "Wrong result type"
      expected = [9]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      assert result is not source["first"]["items"]
      result.append(10)
      assert source == before
      Why are both a token set and page budget needed?

      Cycles repeat tokens; a never-ending fresh-token chain does not. For p pages and n items, work is O(p+n) under ordinary hash lookup and output storage is O(n), with p bounded by four.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: deduplicate across page boundaries

      The reporting requirement changes: return the first occurrence of each integer item across the complete bounded traversal, not every occurrence.

      The contract

      • Input has the same trusted fixture schema as collect_pages, but each item is an integer.
      • Visit every page through next=None with the same four-page and repeated-token errors; keep first-seen item order and remove duplicates across pages.
      • Do not mutate fixtures. Return a fresh list, including [] when no items occur. No HTTP, timing or provider claims follow.
      Transfer: deduplicate across page boundariesPYTHON 3

      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.

      1. cross-page duplicates
        import copy
        
        source = {"first":{"items":[3,1],"next":"p2"},"p2":{"items":[1,2,3],"next":None}}
        before = copy.deepcopy(source)
        result = unique_page_items(source)
        assert type(result) is list, "Wrong result type"
        expected = [3, 1, 2]
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        
      2. no items
        import copy
        
        source = {"first":{"items":[],"next":None}}
        before = copy.deepcopy(source)
        result = unique_page_items(source)
        assert type(result) is list, "Wrong result type"
        expected = []
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        
      3. within-page duplicates
        import copy
        
        source = {"first":{"items":[4,4,4],"next":None}}
        before = copy.deepcopy(source)
        result = unique_page_items(source)
        assert type(result) is list, "Wrong result type"
        expected = [4]
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        
      4. empty page still follows
        import copy
        
        source = {"first":{"items":[],"next":"p2"},"p2":{"items":[0,-1],"next":None}}
        before = copy.deepcopy(source)
        result = unique_page_items(source)
        assert type(result) is list, "Wrong result type"
        expected = [0, -1]
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        
      5. all-duplicate page still follows
        import copy
        
        source = {"first":{"items":[2],"next":"p2"},"p2":{"items":[2],"next":"p3"},"p3":{"items":[1],"next":None}}
        before = copy.deepcopy(source)
        result = unique_page_items(source)
        assert type(result) is list, "Wrong result type"
        expected = [2, 1]
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        for bad in [{"first":{"items":[1],"next":"first"}}, {key: {"items":[], "next": (["p2","p3","p4","p5",None][index])} for index, key in enumerate(["first","p2","p3","p4","p5"])}]:
            snapshot = copy.deepcopy(bad)
            caught = False
            try:
                unique_page_items(bad)
            except ValueError:
                caught = True
            assert caught and bad == snapshot
      6. independent output list
        import copy
        
        source = {"first":{"items":[7,5],"next":None}}
        before = copy.deepcopy(source)
        result = unique_page_items(source)
        assert type(result) is list, "Wrong result type"
        expected = [7, 5]
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        result.clear()
        assert source == before
        assert result is not source["first"]["items"]
        Why is sorting the deduplicated output wrong?

        The changed contract still preserves first appearance. For n items, u distinct items and p bounded pages, ordinary average work is O(n+p) and extra membership plus output storage is O(u+p), not a fixed memory bound for all possible item counts.

        A GOOD PLACE TO PAUSE

        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 milestone

        Actual network lab

        A timeout leaves uncertainty about what happened remotely. Retrying is a policy decision requiring bounded attempts and safe operation semantics.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A read fixture can be retried after a declared temporary failure, but a repeated write can duplicate an effect whose first response was lost.

        Words you will see

        Idempotent
        An operation whose repeated application has the same intended effect as one application under its contract.
        Retry budget
        A bound on repeated attempts and total elapsed work.
        Backoff
        A delay policy between retries, normally bounded by the overall deadline.

        Retry only the declared temporary case

        The local read fixture fails once with TimeoutError, then returns a fixed page. The loop allows two attempts and re-raises a final timeout. It does not catch schema ValueError or every possible exception.

        The output reports two fixture calls, not elapsed time or a real timeout experiment. There is deliberately no sleep, network or random delay. A real retry implementation also budgets waiting, transport time and cancellation under a total deadline.

        Separate reads from uncertain effects

        An eligible read may tolerate retry. A payment or deletion needs a server-enforced idempotency contract, including outcome recovery and incompatible-key rejection. A client loop cannot invent exactly-once behavior.

        A permanent malformed response will not become valid simply because it is fetched again. Classify failure types and respect provider retry policy. Keep destinations approved across retries and redirects; do not broaden network permissions to make a demonstration succeed.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. calls.append(1)

          Record a local invocation without using a clock.

        2. raise TimeoutError("temporary fixture")

          Simulate the explicitly retryable first failure.

        3. for attempt in range(2):

          Bound the number of attempts.

        4. if attempt == 1:

          Propagate a final timeout rather than claiming success.

        For a service you control, use an approved HTTP client with an explicit timeout, check status, bound the body and validate decoded fields. Test connection failure, delayed response, malformed JSON, 429/Retry-After and a repeated pagination token using a local fixture server, not a public site's uncontrolled availability.

        Predict before you run

        How many fixture calls occur?

        Bound a temporary read retry offlinePYTHON 3

        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.

        Remove the temporary failure.

        Try: Delete the if block in read.

        One call succeeds; no retry is needed.

        Make every call time out.

        Try: Raise TimeoutError on every invocation.

        The second failure propagates; no success output is fabricated.

        Before you move on

        A POST times out after the server may have committed it. Does adding three retries guarantee one effect?

        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. Retries can duplicate effects. Use a documented server idempotency key and outcome recovery, or report the uncertainty.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Safe retries and destinations

        An approved destination policy limits where a client may send requests. Response links remain untrusted data even when they came from an approved service.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A pagination or redirect link can move a client to another host or scheme. Validating the final resolved destination prevents treating external text as new authority.

        Words you will see

        Origin
        A combination of scheme, host and effective port.
        Relative link
        A reference resolved against a base URL.
        Redirect
        A response asking the client to use another destination.

        Resolve, then check

        urljoin resolves /pages/2 against the fictional HTTPS base. urlsplit then exposes scheme, hostname and port for an explicit comparison. The reserved example.test host is only text; this program opens no socket.

        Comparing a raw string prefix is insufficient: a different hostname can share the same initial text. User information, unexpected ports and scheme changes also deserve explicit policy. A real adapter should revalidate every redirect rather than relying on its first URL.

        Keep the demonstration scoped

        This small check illustrates one exact origin, not a complete defense for arbitrary user-supplied URLs. Real deployments also address DNS resolution, address ranges, proxy behavior and credential scoping with approved infrastructure.

        A token-only API can avoid accepting arbitrary next URLs at all. Prefer the narrowest documented interface. Browser restrictions and the sandbox's network boundary remain in force; never bypass them to make an example look connected.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. base = "https://example.test/api/"

          Supply a reserved fictional host as data only.

        2. resolved = urljoin(base, link)

          Resolve the relative reference before validation.

        3. parts = urlsplit(resolved)

          Inspect parsed URL components, not a raw prefix.

        4. print(approved)

          Display the exact-origin policy result without fetching.

        Retry only eligible failures within a total budget, and distinguish idempotent reads from writes with uncertain outcomes. Validate redirects and next links. A tutorial download is not permission to probe cloud metadata, local services or arbitrary user-provided URLs.

        Predict before you run

        Is urljoin making a request?

        Check a resolved fictional destination offlinePYTHON 3

        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.

        Change the host.

        Try: Set link to "https://other.test/pages/2".

        The resolved host changes and approved becomes False.

        Change the scheme.

        Try: Set link to "http://example.test/pages/2".

        The HTTPS-only policy rejects the new destination.

        Before you move on

        The first destination is approved, but a redirect points elsewhere. Is checking only the first URL sufficient?

        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. Revalidate each destination under the same policy and do not forward scoped credentials to an unapproved origin.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        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.

        REFLECT, THEN CONTINUE

        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.

        Your account

        Loading account...

        Sign in to save your work across devices.