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 71 / PROJECTS AND ASSESSMENTS

Project: a small database-backed service

Build a service layer that validates study sessions and writes them transactionally to an isolated database. Start with an in-memory SQLite repository; an HTTP layer is a separate adapter, not an excuse to mix request parsing into SQL.

AdvancedProject 40 min core+25 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 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

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.

Disposable SQLite examples are available; a persistent multi-user API/database service needs a separately approved long-running lab.

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
  • Translate requirements into contracts
  • Implement and test a complete small slice
  • Explain production gaps and next increments
BUILD / TEST / EXPLAIN

Project brief and review

Build a service layer that validates study sessions and writes them transactionally to an isolated database. Start with an in-memory SQLite repository; an HTTP layer is a separate adapter, not an excuse to mix request parsing into SQL. Reading time does not include your independent implementation time.

Requirements

  • Validate topic and nonnegative integer minutes.
  • Use parameterised SQL.
  • Keep a service function separate from transport.
  • Close the connection and test rollback behaviour.

Acceptance checklist

These self-checks are page-local, not saved or automatically judged.

Further increments

  • Add a local HTTP adapter with input-size and authentication controls.
  • Run integration tests against the intended deployment database before claiming equivalent concurrency behaviour.

Build this as a multi-file project: Disposable SQLite service boundary

A short-lived disposable local SQLite file created by each test and always closed/deleted, never the application database, a shared database session, HTTP server or cloud service. The service owns one transaction on an idle caller-owned connection and rejects pre-existing transactions rather than committing unrelated work. No PostgreSQL or deployed-service equivalence is claimed. The lesson's single-file browser runner does not import these files.

  1. 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.
  2. Implement validate_session(topic, minutes) in domain.py. Trim a nonblank exact string topic; accept exact nonnegative integer minutes including zero and excluding bool. Keep validation outside SQL.
  3. Implement create_schema, insert_session and insert_audit in repository.py. Bind all values with SQL parameters. Insert helpers participate in a transaction without committing or closing a caller connection. Implement add_session in service.py: validate first, reject an already-active transaction, commit before returning an id, and roll back injected after_insert failures.
  4. Implement add_audited_session(connection, topic, minutes, fail_stage=0) in transfer.py. Session and audit row must commit together. Stages 1 (after session) and 2 (after audit) inject RuntimeError and roll back both. Validate stage as an exact int in 0..2. Compare actual file-backed rows before/after and confirm the caller still owns a usable connection.
  5. Save snapshot explicitly, then Run current files to execute main.py's 11 public standard-library tests. The suite stops at the first failure; the untouched starter raises a real NotImplementedError. Inspect the named failing case, edit and rerun. Add an original test and explain why it would catch a tempting wrong approach.
  6. 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.

01

Project brief and boundaries

A service contract decides which study sessions are valid before a storage adapter decides how to write them.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Mixing HTTP parsing, domain rules and SQL makes it hard to prove that rejected input creates no row or that a successful receipt means a committed write.

Words you will see

Domain rule
A requirement about the meaning of values rather than their transport.
Repository
The boundary that reads and writes stored records.
Validation
Checking allowed shape, type and range before accepting a value.

Turn the brief into explicit values

A topic must be a nonblank string; trim only its surrounding whitespace. Minutes must be an exact nonnegative integer, so zero is valid and True is invalid despite bool being an int subclass. Decide whether case remains significant; this project preserves it. A missing minutes field must not quietly default to zero.

The sample normalizes one already-valid record without changing its source dictionary. Build a pure batch validator first, returning fresh tuples in input order and retaining duplicates. Validate a late bad record too. No partial normal result should escape. Then test the repository with valid rows, rejected rows and SQL-like text before adding any HTTP adapter.

Assign each boundary an owner

The caller owns request records. The service owns validation; the repository owns statements; a named transaction owner decides commit or rollback. The component that opens a connection must close it, unless ownership is explicitly transferred. A borrowed connection must not be closed unexpectedly by a small validation helper.

An ORM may reduce statement boilerplate but adds mapping behavior that also needs testing. Plain parameterized SQL makes this small boundary easier to inspect. For n flat sessions the pure normalization pass takes O(n) work plus string trimming and O(n) returned tuples. Browser exercises below use only data models; real connection lifecycle, constraint behavior and rollback belong in a separate local database lab.

The original example, step by step

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

  1. request = {"topic": " lists ", "minutes": 0}

    Supply a caller-owned request with a valid zero.

  2. topic = request["topic"].strip()

    Create a normalized string, not an assignment into request.

  3. normalized = (topic, minutes)

    Build a separate immutable pair.

  4. print(request["topic"] == " lists ")

    Check that the original spelling is unchanged.

Build a service layer that validates study sessions and writes them transactionally to an isolated database. Start with an in-memory SQLite repository; an HTTP layer is a separate adapter, not an excuse to mix request parsing into SQL.

Conceptual service boundaries, not a deployed request trace

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

  1. TransportDecode and authorize a request; no transport runs here.
  2. ServiceValidate domain values and choose the transaction boundary.
  3. RepositoryBind values, commit or roll back, then release owned resources.
Predict before you run

What happens to the original topic in this sample?

Normalize without changing the requestPYTHON 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.

Try a zero-length normalized topic.

Try: Change the topic to " ".

The demonstration produces an empty string. The validator exercise must reject it; this sample assumes validity.

Keep a meaningful case difference.

Try: Change the topic to " Lists ".

The pair contains 'Lists', not 'lists'.

Before you move on

Should topics 'SQL' and 'sql' be combined by this normalization rule?

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. Trimming does not fold case, and the brief does not request grouping. Both are separate session records even if their spelling is identical.

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

Design a testable slice

A transaction groups changes so they become visible together or do not become committed at all. A successful response must follow commit.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A session and its related state must not be half-written when a later step fails. A private data model can clarify the contract before introducing SQL.

Words you will see

Commit
Make a transaction's changes authoritative.
Rollback
Discard uncommitted changes after failure.
Atomicity
Treating a group of changes as one all-or-nothing unit.

Separate candidate state from committed state

The sample copies existing rows, appends a candidate, then injects a failure. It returns an explicitly unsuccessful outcome with the old rows. This is a deterministic model, not a real database transaction. A production service might instead raise an exception; the model uses a committed boolean to make both possible states inspectable.

The caller still owns the existing list. Copy before appending, and return a fresh list even on rollback. That rule prevents someone modifying the modeled outcome from changing the caller's saved snapshot. With supported immutable string/integer tuples, one outer list copy is enough; arbitrary nested payloads would require a different copy-depth contract.

Build from failure outward

Implement success and rollback models, then test actual repository rollback by failing between dependent SQL statements. Query persisted state after the failed transaction and verify no partial committed write. Mock call counts alone cannot establish database state. Helpers must not commit independently when an outer unit owns both writes.

Candidate copying uses O(r + a) work and space for r existing rows and a additions. A real database uses its own transaction mechanisms rather than copying all rows in Python. Savepoints can isolate part of a larger unit but complicate ownership. Keep browser model evidence separate from local SQLite integration, then test the intended deployment engine before making concurrency or isolation claims.

The original example, step by step

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

  1. rows = [("lists", 10)]

    Describe the previously committed snapshot.

  2. candidate = list(rows)

    Create an independent mutable container.

  3. candidate.append(("loops", 5))

    Stage a proposed addition privately.

  4. outcome = {"committed": not failed

    Choose explicit rollback instead of claiming the candidate committed.

The service validates domain values, then calls a repository/transaction boundary. Bind data as SQL parameters and test the count after rejected input. A returned identifier or receipt should refer to a committed operation, not a promise made before commit.

Predict before you run

Which rows appear in the failed outcome?

Model commit and rollback explicitlyPYTHON 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.

Commit the candidate.

Try: Change failed to False.

The outcome contains both rows and committed is True.

Probe return ownership.

Try: Append outcome["rows"].append(("new", 1)); then print(rows).

rows still contains only its original row because each branch uses a private list.

Before you move on

If a failed model returns the caller's original rows object unchanged, is the ownership promise satisfied?

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

Not fully. Its values are unchanged now, but later mutation through the result would change caller data. Return a fresh outer list for this flat supported shape.

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

Validate then persist

The original repository fixture validates and persists one session using bound SQL values and a privately owned in-memory SQLite connection.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

The project needs actual persistence evidence as well as policy tests. This narrow reference shows a real connection lifecycle without files, credentials or an HTTP server.

Words you will see

Bound parameter
A data value passed separately from SQL statement syntax.
Connection
The handle through which code uses a database.
In-memory database
A database kept in process memory for this fixture's lifetime.

Read the preserved storage slice

add_session checks topic shape, nonblank spelling, exact integer type and nonnegative range. Inside the connection context it executes a fixed INSERT with two placeholders and a tuple of values. The valid lists session commits on normal exit; the negative loops session raises before executing SQL. The fixture catches only that expected validation error and reads the remaining row.

The outer try/finally closes the connection opened by the fixture. The connection context controls the transaction; it does not close the handle. This ownership split matters. The function uses a connection supplied by its caller, and its context can affect transaction ownership. Do not reuse it inside an unrelated larger unit without defining who may commit.

Retain the evidence boundary

The reference uses stdlib sqlite3 and ':memory:' only. It has no persistent file, live network, database credential or server. A browser runtime must actually support sqlite3 before this example can execute there; do not replace an unavailable module with fabricated output. The new browser exercise increments use data only and need no SQLite module.

Run independent local SQLite tests for literal SQL-like text, invalid input leaving the count unchanged, and an injected exception between writes rolling back both. Add schema constraints as defense in depth. This reference does not itself inject a transaction failure or prove concurrent deployment behavior. An HTTP adapter, migrations, authentication and target-engine integration remain real local lab work, not a completed deployment.

The original example, step by step

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

  1. if not isinstance(topic, str)

    Begin domain validation before entering SQL.

  2. with connection:

    Use the caller-supplied connection's transaction context.

  3. connection.execute('INSERT INTO sessions VALUES (?, ?)', (topic.strip(), minutes))

    Keep values separate from statement syntax.

  4. connection.close()

    Release the connection owned by the outer fixture.

The known validation exception is handled only in this test fixture so the assertion/report can inspect persisted state. The service itself raises errors and uses bound values.

Predict before you run

How many rows does the final query return?

Validate then persistPYTHON 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.

Permit the second session.

Try: Change the rejected minutes from -1 to 0.

Both sessions are stored; zero is valid.

Store punctuation literally.

Try: Change the first topic to "SQL; --".

That exact text is stored as data through the bound parameter.

Before you move on

If topic contains a quote followed by SQL-looking words, do the placeholders execute those words?

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. Bound values are stored as data, not added to SQL syntax. That does not replace authorization or validation; it addresses the statement/data boundary.

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

Design domain, repository and transport boundaries

The service accepts a nonblank string topic and exact nonnegative integer minutes, trims the topic, and persists the validated session through parameterized SQL. A domain service decides validity; a repository owns statements and transaction participation; any HTTP adapter owns request decoding, authentication, and response mapping. Define connection ownership explicitly so a helper neither closes a caller-owned connection unexpectedly nor commits unrelated work that the caller intended to group atomically.

The reference uses a private in-memory SQLite sessions table, inserts lists with 20, rejects loops with negative minutes, and prints the one persisted row before closing in finally. It demonstrates validation, bound values, and a local transaction boundary. It has no HTTP server, user authorization, persistent database file, migrations, or PostgreSQL concurrency behavior. Calling it a service layer does not mean the executable slice has established deployed service readiness.

Implement numbered slices and define committed success

1. Write domain validation tests, especially bool rejection through the exact integer rule. 2. Add a fresh database schema and one repository insert/read test. 3. Connect the service to the repository with an explicit transaction owner. 4. Inject a failure between dependent writes and prove rollback. 5. Add constraints and SQL-like input tests. 6. Introduce an HTTP adapter only after the persistence boundary has independent evidence.

Do not return a committed identifier before the transaction actually commits. If the service later writes both a session and an audit row, they should share the intended transaction. A helper-level commit can otherwise break the caller's all-or-nothing assumption. Database constraints complement domain validation but do not replace authorization or safe errors. Preserve unexpected defects for diagnosis instead of catching every database exception and pretending the insert produced an empty successful result.

Specify acceptance cases across failure boundaries

Unit tests cover trimmed topics, blank or nonstring topics, zero minutes, negative values, booleans, and noninteger numbers. Repository integration tests verify a valid row is readable, rejected input leaves the count unchanged, and text containing SQL syntax is stored literally. Inject a transaction failure after an initial write and assert no partial committed state. Use fresh isolated state per test and check actual rows, not merely whether execute was called.

Test connection cleanup on success and exception at the component that owns it. If an HTTP adapter is added, separately verify payload-size limits, schema errors, authentication, authorization, safe error responses, and the mapping from committed results to status codes. For the intended deployment database, test unique conflicts, rollback, and concurrent access using its actual isolation behavior. An in-memory SQLite pass cannot be promoted into proof that another engine's locks, pool limits, or migrations behave identically.

Scope operational hardening and independent effort

Bound topic length, request size, query result size, connection waiting, and transaction duration. Decide whether duplicate requests create separate sessions or share a stable request identity with a receipt. A local transaction cannot undo an external notification; add an outbox or a documented recovery mechanism when side effects cross systems. Closing a connection is cleanup, not a backup strategy. Real persistence requires tested migration and restore procedures plus an access-control model.

Allocate focused sessions for domain rules, repository rollback tests, and adapter integration, leaving deployment work as a separately reviewed stage. Implement each stage before opening its reference and keep your own failing test evidence. Record unsupported features such as multi-user access or crash recovery rather than implying them through architectural names. A good self-review explains why every resource has an owner, when success becomes authoritative, and which remaining risks require environment-specific tests.

Transfer question: The service must now insert a session and update a daily summary atomically. What changes in implementation and acceptance?

Move transaction ownership to the unit of work containing both statements so neither helper commits independently. Validate the session first, insert it, update the correct day-topic summary, and commit only after both succeed. Define the day's timezone and concurrent-update strategy, using database operations that avoid lost updates under the chosen isolation. Inject a failure after insertion and verify both tables remain unchanged; test two concurrent updates against the deployment engine. Keep notification delivery outside this local atomic claim unless it has an explicit recovery protocol. The existing single-table SQLite fixture does not prove these expanded guarantees.

RECALL BEFORE YOU SCROLL

Can you explain it?

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

When is this project ready for your self-review?
TRANSFER THE IDEA

Build before opening the reference

Validate topic and nonnegative integer minutes. Use parameterised SQL. Keep a service function separate from transport. Close the connection and test rollback behaviour. Demonstrate the acceptance cases and document any unsupported requirement.

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

Increment 1: validate a session batch

Extract the service's domain rule as a pure browser-local batch calculation.

The contract

  • records is an exact list of exact dictionaries containing topic and minutes. Extra fields are ignored but never changed, including nested metadata.
  • topic is an exact string, stripped but not case-folded, and must remain nonempty. minutes is an exact nonnegative int; missing fields and bool are invalid. Raise ValueError for any invalid record, including late records.
  • Return a new list of (normalized_topic, minutes) tuples, retaining input order and duplicate sessions. No caller mutation, SQL connection or I/O.
Increment 1: validate a session batchPYTHON 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. Trim, preserve case and duplicates
    from copy import deepcopy
    arguments = ([{'topic': ' SQL ', 'minutes': 0, 'metadata': {'tags': ['x']}}, {'topic': 'SQL', 'minutes': 2}, {'topic': 'sql', 'minutes': 1}],)
    before = deepcopy(arguments)
    try:
        result = normalize_sessions(*arguments)
    except ValueError:
        result = ("ValueError",)
    assert arguments == before, "Caller input changed"
    expected = [('SQL', 0), ('SQL', 2), ('sql', 1)]
    assert type(result) is type(expected), "Wrong result type"
    assert result == expected, "Wrong result value"
    def check_types(actual, target):
        assert type(actual) is type(target), "Wrong nested result type"
        if type(target) in (list, tuple):
            for item, wanted in zip(actual, target):
                check_types(item, wanted)
        elif type(target) is dict:
            for key in target:
                check_types(actual[key], target[key])
    check_types(result, expected)
    if type(result) is list:
        result.append(("ownership-probe", 0))
    elif type(result) is dict:
        for value in result.values():
            if type(value) is list:
                value.append(("ownership-probe", 0))
    assert arguments == before, "Caller input changed through result alias"
    
  2. Empty batch
    from copy import deepcopy
    arguments = ([],)
    before = deepcopy(arguments)
    try:
        result = normalize_sessions(*arguments)
    except ValueError:
        result = ("ValueError",)
    assert arguments == before, "Caller input changed"
    expected = []
    assert type(result) is type(expected), "Wrong result type"
    assert result == expected, "Wrong result value"
    def check_types(actual, target):
        assert type(actual) is type(target), "Wrong nested result type"
        if type(target) in (list, tuple):
            for item, wanted in zip(actual, target):
                check_types(item, wanted)
        elif type(target) is dict:
            for key in target:
                check_types(actual[key], target[key])
    check_types(result, expected)
    if type(result) is list:
        result.append(("ownership-probe", 0))
    elif type(result) is dict:
        for value in result.values():
            if type(value) is list:
                value.append(("ownership-probe", 0))
    assert arguments == before, "Caller input changed through result alias"
    
  3. SQL-looking text is data
    from copy import deepcopy
    arguments = ([{'topic': "x'); DROP TABLE sessions; --", 'minutes': 1}],)
    before = deepcopy(arguments)
    try:
        result = normalize_sessions(*arguments)
    except ValueError:
        result = ("ValueError",)
    assert arguments == before, "Caller input changed"
    expected = [("x'); DROP TABLE sessions; --", 1)]
    assert type(result) is type(expected), "Wrong result type"
    assert result == expected, "Wrong result value"
    def check_types(actual, target):
        assert type(actual) is type(target), "Wrong nested result type"
        if type(target) in (list, tuple):
            for item, wanted in zip(actual, target):
                check_types(item, wanted)
        elif type(target) is dict:
            for key in target:
                check_types(actual[key], target[key])
    check_types(result, expected)
    if type(result) is list:
        result.append(("ownership-probe", 0))
    elif type(result) is dict:
        for value in result.values():
            if type(value) is list:
                value.append(("ownership-probe", 0))
    assert arguments == before, "Caller input changed through result alias"
    
  4. Late bool minutes
    from copy import deepcopy
    arguments = ([{'topic': 'ok', 'minutes': 1}, {'topic': 'bad', 'minutes': True}],)
    before = deepcopy(arguments)
    try:
        result = normalize_sessions(*arguments)
    except ValueError:
        result = ("ValueError",)
    assert arguments == before, "Caller input changed"
    expected = ("ValueError",)
    assert type(result) is type(expected), "Wrong result type"
    assert result == expected, "Wrong result value"
    def check_types(actual, target):
        assert type(actual) is type(target), "Wrong nested result type"
        if type(target) in (list, tuple):
            for item, wanted in zip(actual, target):
                check_types(item, wanted)
        elif type(target) is dict:
            for key in target:
                check_types(actual[key], target[key])
    check_types(result, expected)
    
    
  5. Blank topic
    from copy import deepcopy
    arguments = ([{'topic': '  ', 'minutes': 1}],)
    before = deepcopy(arguments)
    try:
        result = normalize_sessions(*arguments)
    except ValueError:
        result = ("ValueError",)
    assert arguments == before, "Caller input changed"
    expected = ("ValueError",)
    assert type(result) is type(expected), "Wrong result type"
    assert result == expected, "Wrong result value"
    def check_types(actual, target):
        assert type(actual) is type(target), "Wrong nested result type"
        if type(target) in (list, tuple):
            for item, wanted in zip(actual, target):
                check_types(item, wanted)
        elif type(target) is dict:
            for key in target:
                check_types(actual[key], target[key])
    check_types(result, expected)
    
    
  6. Missing minutes
    from copy import deepcopy
    arguments = ([{'topic': 'api'}],)
    before = deepcopy(arguments)
    try:
        result = normalize_sessions(*arguments)
    except ValueError:
        result = ("ValueError",)
    assert arguments == before, "Caller input changed"
    expected = ("ValueError",)
    assert type(result) is type(expected), "Wrong result type"
    assert result == expected, "Wrong result value"
    def check_types(actual, target):
        assert type(actual) is type(target), "Wrong nested result type"
        if type(target) in (list, tuple):
            for item, wanted in zip(actual, target):
                check_types(item, wanted)
        elif type(target) is dict:
            for key in target:
                check_types(actual[key], target[key])
    check_types(result, expected)
    
    
    Why keep duplicate sessions?

    Each tuple contains immutable supported values, so the new outer list owns all mutable output containers. For n records, work is linear plus topic-trimming cost and output is O(n). Invalid input raises without exposing the private partial list. The service stores events, not unique topics. Deduplication would be a changed requirement needing an identity policy.

    GUIDED PRACTICE

    Increment 2: stage a modeled transaction

    Specify success and rollback with explicit outcome data before testing real SQL transactions locally.

    The contract

    • existing and additions are exact lists of normalized two-item tuples (nonempty stripped exact string, exact nonnegative integer). Validate all rows before staging.
    • fail_after is an exact integer from 0 to len(additions). Zero means no injected failure; positive k fails after staging the kth addition. Invalid input raises ValueError.
    • Return exactly {'committed': bool, 'rows': fresh_list}. Failure retains only existing rows; success includes every addition in order, preserving duplicates. No aliases to caller lists, database access or I/O.
    Increment 2: stage a modeled transactionPYTHON 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. Commit duplicates
      from copy import deepcopy
      arguments = ([('a', 1)], [('a', 0), ('b', 2)], 0)
      before = deepcopy(arguments)
      try:
          result = commit_model(*arguments)
      except ValueError:
          result = ("ValueError",)
      assert arguments == before, "Caller input changed"
      expected = {'committed': True, 'rows': [('a', 1), ('a', 0), ('b', 2)]}
      assert type(result) is type(expected), "Wrong result type"
      assert result == expected, "Wrong result value"
      def check_types(actual, target):
          assert type(actual) is type(target), "Wrong nested result type"
          if type(target) in (list, tuple):
              for item, wanted in zip(actual, target):
                  check_types(item, wanted)
          elif type(target) is dict:
              for key in target:
                  check_types(actual[key], target[key])
      check_types(result, expected)
      if type(result) is list:
          result.append(("ownership-probe", 0))
      elif type(result) is dict:
          for value in result.values():
              if type(value) is list:
                  value.append(("ownership-probe", 0))
      assert arguments == before, "Caller input changed through result alias"
      
    2. Empty transaction
      from copy import deepcopy
      arguments = ([], [], 0)
      before = deepcopy(arguments)
      try:
          result = commit_model(*arguments)
      except ValueError:
          result = ("ValueError",)
      assert arguments == before, "Caller input changed"
      expected = {'committed': True, 'rows': []}
      assert type(result) is type(expected), "Wrong result type"
      assert result == expected, "Wrong result value"
      def check_types(actual, target):
          assert type(actual) is type(target), "Wrong nested result type"
          if type(target) in (list, tuple):
              for item, wanted in zip(actual, target):
                  check_types(item, wanted)
          elif type(target) is dict:
              for key in target:
                  check_types(actual[key], target[key])
      check_types(result, expected)
      if type(result) is list:
          result.append(("ownership-probe", 0))
      elif type(result) is dict:
          for value in result.values():
              if type(value) is list:
                  value.append(("ownership-probe", 0))
      assert arguments == before, "Caller input changed through result alias"
      
    3. Rollback after first
      from copy import deepcopy
      arguments = ([('old', 1)], [('a', 2), ('b', 3)], 1)
      before = deepcopy(arguments)
      try:
          result = commit_model(*arguments)
      except ValueError:
          result = ("ValueError",)
      assert arguments == before, "Caller input changed"
      expected = {'committed': False, 'rows': [('old', 1)]}
      assert type(result) is type(expected), "Wrong result type"
      assert result == expected, "Wrong result value"
      def check_types(actual, target):
          assert type(actual) is type(target), "Wrong nested result type"
          if type(target) in (list, tuple):
              for item, wanted in zip(actual, target):
                  check_types(item, wanted)
          elif type(target) is dict:
              for key in target:
                  check_types(actual[key], target[key])
      check_types(result, expected)
      if type(result) is list:
          result.append(("ownership-probe", 0))
      elif type(result) is dict:
          for value in result.values():
              if type(value) is list:
                  value.append(("ownership-probe", 0))
      assert arguments == before, "Caller input changed through result alias"
      
    4. Rollback after final
      from copy import deepcopy
      arguments = ([], [('a', 2)], 1)
      before = deepcopy(arguments)
      try:
          result = commit_model(*arguments)
      except ValueError:
          result = ("ValueError",)
      assert arguments == before, "Caller input changed"
      expected = {'committed': False, 'rows': []}
      assert type(result) is type(expected), "Wrong result type"
      assert result == expected, "Wrong result value"
      def check_types(actual, target):
          assert type(actual) is type(target), "Wrong nested result type"
          if type(target) in (list, tuple):
              for item, wanted in zip(actual, target):
                  check_types(item, wanted)
          elif type(target) is dict:
              for key in target:
                  check_types(actual[key], target[key])
      check_types(result, expected)
      if type(result) is list:
          result.append(("ownership-probe", 0))
      elif type(result) is dict:
          for value in result.values():
              if type(value) is list:
                  value.append(("ownership-probe", 0))
      assert arguments == before, "Caller input changed through result alias"
      
    5. Validate tail before staging
      from copy import deepcopy
      arguments = ([], [('a', 1), ('bad', True)], 1)
      before = deepcopy(arguments)
      try:
          result = commit_model(*arguments)
      except ValueError:
          result = ("ValueError",)
      assert arguments == before, "Caller input changed"
      expected = ("ValueError",)
      assert type(result) is type(expected), "Wrong result type"
      assert result == expected, "Wrong result value"
      def check_types(actual, target):
          assert type(actual) is type(target), "Wrong nested result type"
          if type(target) in (list, tuple):
              for item, wanted in zip(actual, target):
                  check_types(item, wanted)
          elif type(target) is dict:
              for key in target:
                  check_types(actual[key], target[key])
      check_types(result, expected)
      
      
    6. Reject bool injection index
      from copy import deepcopy
      arguments = ([], [], False)
      before = deepcopy(arguments)
      try:
          result = commit_model(*arguments)
      except ValueError:
          result = ("ValueError",)
      assert arguments == before, "Caller input changed"
      expected = ("ValueError",)
      assert type(result) is type(expected), "Wrong result type"
      assert result == expected, "Wrong result value"
      def check_types(actual, target):
          assert type(actual) is type(target), "Wrong nested result type"
          if type(target) in (list, tuple):
              for item, wanted in zip(actual, target):
                  check_types(item, wanted)
          elif type(target) is dict:
              for key in target:
                  check_types(actual[key], target[key])
      check_types(result, expected)
      
      
      Does returning the old list object on failure count as safe rollback?

      The result names rollback rather than disguising it as a successful empty write. With r existing and a added rows, validation and copying cost O(r + a), using O(r + a) model storage. A real database transaction must be tested separately. Its current value is right but its ownership is wrong. Later callers could mutate the original snapshot through the returned rows.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: session and audit commit together

      Expand the commit boundary to two related outputs, not two independently successful writes.

      The contract

      • rows is an exact list of normalized (nonempty stripped exact string, exact nonnegative int) tuples. audit is an exact list of strings. Validate both snapshots.
      • session is an exact dict with a nonblank exact string topic and exact nonnegative integer minutes; trim topic, retain case, ignore extra fields. fail_stage is exact int 0, 1 or 2. Invalid input raises ValueError.
      • Stage 0 commits one normalized session plus audit text 'added:{topic}:{minutes}'. Stages 1 and 2 fail after the respective modeled write and roll back both lists. Return exactly committed, rows and audit fields with fresh lists; preserve all inputs and duplicates. Browser data model only; actual SQL atomicity requires a local lab.
      Transfer: session and audit commit togetherPYTHON 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. Commit both, retain duplicates
        from copy import deepcopy
        arguments = ([('a', 0)], ['older'], {'topic': ' a ', 'minutes': 0}, 0)
        before = deepcopy(arguments)
        try:
            result = apply_unit(*arguments)
        except ValueError:
            result = ("ValueError",)
        assert arguments == before, "Caller input changed"
        expected = {'committed': True, 'rows': [('a', 0), ('a', 0)], 'audit': ['older', 'added:a:0']}
        assert type(result) is type(expected), "Wrong result type"
        assert result == expected, "Wrong result value"
        def check_types(actual, target):
            assert type(actual) is type(target), "Wrong nested result type"
            if type(target) in (list, tuple):
                for item, wanted in zip(actual, target):
                    check_types(item, wanted)
            elif type(target) is dict:
                for key in target:
                    check_types(actual[key], target[key])
        check_types(result, expected)
        if type(result) is list:
            result.append(("ownership-probe", 0))
        elif type(result) is dict:
            for value in result.values():
                if type(value) is list:
                    value.append(("ownership-probe", 0))
        assert arguments == before, "Caller input changed through result alias"
        
      2. Commit into empty snapshots
        from copy import deepcopy
        arguments = ([], [], {'topic': 'loops', 'minutes': 2}, 0)
        before = deepcopy(arguments)
        try:
            result = apply_unit(*arguments)
        except ValueError:
            result = ("ValueError",)
        assert arguments == before, "Caller input changed"
        expected = {'committed': True, 'rows': [('loops', 2)], 'audit': ['added:loops:2']}
        assert type(result) is type(expected), "Wrong result type"
        assert result == expected, "Wrong result value"
        def check_types(actual, target):
            assert type(actual) is type(target), "Wrong nested result type"
            if type(target) in (list, tuple):
                for item, wanted in zip(actual, target):
                    check_types(item, wanted)
            elif type(target) is dict:
                for key in target:
                    check_types(actual[key], target[key])
        check_types(result, expected)
        if type(result) is list:
            result.append(("ownership-probe", 0))
        elif type(result) is dict:
            for value in result.values():
                if type(value) is list:
                    value.append(("ownership-probe", 0))
        assert arguments == before, "Caller input changed through result alias"
        
      3. Failure after session
        from copy import deepcopy
        arguments = ([('old', 1)], ['older'], {'topic': 'new', 'minutes': 2}, 1)
        before = deepcopy(arguments)
        try:
            result = apply_unit(*arguments)
        except ValueError:
            result = ("ValueError",)
        assert arguments == before, "Caller input changed"
        expected = {'committed': False, 'rows': [('old', 1)], 'audit': ['older']}
        assert type(result) is type(expected), "Wrong result type"
        assert result == expected, "Wrong result value"
        def check_types(actual, target):
            assert type(actual) is type(target), "Wrong nested result type"
            if type(target) in (list, tuple):
                for item, wanted in zip(actual, target):
                    check_types(item, wanted)
            elif type(target) is dict:
                for key in target:
                    check_types(actual[key], target[key])
        check_types(result, expected)
        if type(result) is list:
            result.append(("ownership-probe", 0))
        elif type(result) is dict:
            for value in result.values():
                if type(value) is list:
                    value.append(("ownership-probe", 0))
        assert arguments == before, "Caller input changed through result alias"
        
      4. Failure after audit
        from copy import deepcopy
        arguments = ([], [], {'topic': 'new', 'minutes': 2}, 2)
        before = deepcopy(arguments)
        try:
            result = apply_unit(*arguments)
        except ValueError:
            result = ("ValueError",)
        assert arguments == before, "Caller input changed"
        expected = {'committed': False, 'rows': [], 'audit': []}
        assert type(result) is type(expected), "Wrong result type"
        assert result == expected, "Wrong result value"
        def check_types(actual, target):
            assert type(actual) is type(target), "Wrong nested result type"
            if type(target) in (list, tuple):
                for item, wanted in zip(actual, target):
                    check_types(item, wanted)
            elif type(target) is dict:
                for key in target:
                    check_types(actual[key], target[key])
        check_types(result, expected)
        if type(result) is list:
            result.append(("ownership-probe", 0))
        elif type(result) is dict:
            for value in result.values():
                if type(value) is list:
                    value.append(("ownership-probe", 0))
        assert arguments == before, "Caller input changed through result alias"
        
      5. Invalid bool session preserves metadata
        from copy import deepcopy
        arguments = ([], [], {'topic': 'x', 'minutes': True, 'metadata': ['keep']}, 0)
        before = deepcopy(arguments)
        try:
            result = apply_unit(*arguments)
        except ValueError:
            result = ("ValueError",)
        assert arguments == before, "Caller input changed"
        expected = ("ValueError",)
        assert type(result) is type(expected), "Wrong result type"
        assert result == expected, "Wrong result value"
        def check_types(actual, target):
            assert type(actual) is type(target), "Wrong nested result type"
            if type(target) in (list, tuple):
                for item, wanted in zip(actual, target):
                    check_types(item, wanted)
            elif type(target) is dict:
                for key in target:
                    check_types(actual[key], target[key])
        check_types(result, expected)
        
        
      6. Invalid stage
        from copy import deepcopy
        arguments = ([], [], {'topic': 'x', 'minutes': 1}, 3)
        before = deepcopy(arguments)
        try:
            result = apply_unit(*arguments)
        except ValueError:
            result = ("ValueError",)
        assert arguments == before, "Caller input changed"
        expected = ("ValueError",)
        assert type(result) is type(expected), "Wrong result type"
        assert result == expected, "Wrong result value"
        def check_types(actual, target):
            assert type(actual) is type(target), "Wrong nested result type"
            if type(target) in (list, tuple):
                for item, wanted in zip(actual, target):
                    check_types(item, wanted)
            elif type(target) is dict:
                for key in target:
                    check_types(actual[key], target[key])
        check_types(result, expected)
        
        
        Would committing the session helper first preserve the two-write contract?

        One owner decides the outcome for both outputs. Immutable fields permit shallow snapshot copies, but the returned lists must be new on every branch. For r rows and a audit strings, model work and extra space are O(r + a), plus topic length. No. A later audit error would leave a partial committed session. The real repository needs one transaction surrounding both statements.

        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

        Production hardening is separate

        A unit of work owns every change that must commit together. Separate repository helpers must participate in that unit rather than decide success independently.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Adding an audit row changes the transaction contract. A session must not remain committed when its required audit write fails.

        Words you will see

        Unit of work
        The complete set of changes sharing one commit decision.
        Audit record
        A record of an operation, with its own defined storage requirements.
        Failure injection
        Deliberately raising or selecting a failure at a known step to test behavior.

        Make the changed requirement precise

        The transfer now stages a session and an audit message. Failure after either stage returns committed False with both prior snapshots. Success exposes both staged additions. Audit text follows a fixed format from normalized topic and minutes. The browser model does not write logs; its returned audit list is test data.

        Validate the entire incoming session before staging any addition. A transaction helper owns both outputs, and each returned list must be independent of caller lists. Existing rows and audits are already-valid snapshots. Preserve duplicate sessions because this transfer does not introduce deduplication or request identities.

        Move from model to integration

        First test no failure, failure after session staging and failure after audit staging. Then implement a local SQLite unit with both statements inside the same transaction. Inject a real exception after the first INSERT and inspect both tables afterward. Do not let either inner helper call commit. The real API may raise; map its errors to safe transport outcomes outside the repository.

        An outbox is appropriate when a required notification crosses into another system, because a local transaction cannot undo a sent message. It adds delivery state and duplicate handling. For r rows and a audit entries, this simple snapshot model copies O(r + a) state; real transaction cost is engine-specific. The browser model proves neither crash recovery nor deployment readiness. Rebuild and explain the two-write project independently.

        The original example, step by step

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

        1. rows, audit = [], []

          Start two independent committed snapshots.

        2. staged_rows, staged_audit = list(rows), list(audit)

          Own both candidate containers.

        3. staged_rows.append(("loops", 5))

          Model the first dependent write.

        4. result = (list(rows), list(audit))

          Rollback selects neither staged change.

        SQLite is a learning fixture, not evidence of production PostgreSQL concurrency semantics. Add migrations, unique request identities where required, access controls, safe error responses and real backup/restore procedures before a deployed service.

        Predict before you run

        What does the failed sample publish?

        Stage two related changesPYTHON 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.

        Publish both candidate changes.

        Try: Set failed_after_session to False.

        The returned pair contains one session and its audit text.

        Start with an older audit.

        Try: Initialize audit as ["older"].

        Rollback preserves that prior audit instead of erasing all history.

        Before you move on

        If the audit write raises after the session INSERT, what should a two-table rollback assertion inspect?

        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

        Both tables. They must match their pre-transaction state; checking only the exception or only the audit count would miss a committed session leak.

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

        Review and transfer

        Database production hardening is a collection of separate contracts: bounded requests, access control, migration, recovery and engine-specific concurrency.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A successful in-memory insert cannot demonstrate a safe multi-user service or a restorable persistent database.

        Words you will see

        Migration
        A controlled change to stored schema or data.
        Isolation
        Rules governing how concurrent transactions observe one another.
        Recovery test
        An actual exercise restoring useful state after a specified failure.

        Bound work before opening resources

        The sample rejects a batch that exceeds a record limit and computes totals only for an allowed batch. In a service, also bound topic length, decoded request size, query result size and transaction duration. A row-count limit does not bound bytes when topics can be arbitrarily large. Enforce limits at the relevant adapter and domain boundaries.

        Decide whether repeated client requests should create repeated sessions. If not, introduce an explicit request identity with a unique constraint and a conflict policy. Merely checking for an existing row before inserting can race. Transaction isolation and constraint behavior must be tested against the intended database engine, not inferred from the SQLite happy path.

        Plan independently verifiable release stages

        Finish validation unit tests, then repository integration, then transport authorization and safe error mapping. Keep credentials outside examples and source. Test schema migration on representative state and perform an actual restore rehearsal locally before claiming recovery. Closing a connection is cleanup, not backup, and a committed receipt is not a restore guarantee.

        The browser limit demonstration and policy exercises use no live network or files. They are not a completed deployment. Independent project work includes target-engine concurrency tests, rollback and connection cleanup under errors, plus a bounded local HTTP adapter if that extension is chosen. Counting n sessions is O(n); real storage, lock waits and restore cost need separate measurements with stated workloads.

        The original example, step by step

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

        1. batch = [("lists", 10), ("loops", 0)]

          Supply a finite, already-valid batch.

        2. limit = 2

          Set an explicit count limit.

        3. accepted = len(batch) <= limit

          Include the exact boundary.

        4. total = sum(minutes for _, minutes in batch) if accepted else None

          Do not calculate a success total for an oversized batch.

        After implementation, explain the boundary cases and change one requirement without rewriting unrelated behaviour. Add a local HTTP adapter with input-size and authentication controls. Run integration tests against the intended deployment database before claiming equivalent concurrency behaviour. Keep a record of what you tested; a viewed reference is not proof you independently completed the project.

        Predict before you run

        Is the exact two-row boundary accepted?

        Check a finite admission limitPYTHON 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.

        Exceed the count limit.

        Try: Set limit to 1.

        accepted becomes False and total becomes None, not a success-looking zero.

        Accept an empty batch.

        Try: Change batch to [].

        It is admitted and totals zero; absence is distinct from rejection.

        Before you move on

        A batch has one row with a million-character topic. Does a ten-row limit alone bound its decoded memory?

        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 row count fits while its text is huge. Add a request-size and field-size contract and enforce each at the appropriate boundary.

        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.