The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← CS 101 — Programming Foundations with Python

Weeks 9–11

Exceptions, files and validated boundaries

Learning objectives

  • Explain and trace the mechanisms in exceptions, files and validated boundaries.
  • Apply the method to the worked example and changed-condition exercise.
  • Identify assumptions, failure cases and the evidence needed to justify a result.
  • Test the added failure-mode fixture and explain which guarantee the evidence does and does not establish.
  • Distinguish CSV syntax, exact schema, lexical amount rules and record/physical-line diagnostics.
  • Explain global identity storage, disk indexing and full-batch publication with precise failure guarantees.
  • Test explicit decoding, resource acquisition/cleanup and JSON duplicate/nonfinite/schema boundaries.

Current study directions: the original Academy lessons, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters and their historical reading directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending.

Data entering a program is not correct merely because it came from a file. Establish an encoding, column names, units and a validation policy. A CSV parser handles delimiters and quoted fields; splitting each line on a comma fails when a quoted customer name itself contains a comma. Open text files with an explicit encoding and use a context manager so the file closes even when an exception occurs.

Catch errors where you can provide a meaningful response. Catching every exception and returning zero confuses a failed calculation with a successful zero result. A conversion error in an amount should identify the record for correction. A missing file is a different condition from a malformed row. Validation should preserve enough context to diagnose the problem without exposing confidential information in logs.

Design the write path as carefully as the read path. If the process overwrites the only copy and stops halfway, valid earlier data may be lost. For a local single-process application, writing a temporary file and replacing the destination after successful completion reduces this failure window. It does not by itself solve concurrent writers, operating-system durability or remote filesystem semantics. Decide whether a batch is all-or-nothing or accepts valid rows while reporting rejects. Either can be appropriate, but silently dropping records produces misleading totals. A clean separation between parsing, validation and calculation lets you test each policy independently.

Worked reasoning The parser returns the quoted company name as one field despite its internal comma. The amount is converted once at the boundary. A malformed amount raises a line-specific exception and no partial result is returned. This is an all-or-nothing in-memory parser, not a file-writing function. It allows refunds because negativity is not forbidden; that policy can be changed separately from CSV syntax.

Extended teaching and laboratory

Parsing asks whether bytes conform to a representation. Validation asks whether the represented record satisfies the domain contract. A syntactically valid CSV row can still contain an unknown customer or an invalid amount. Report the location and rule violated without leaking unrelated records.

Atomicity is a separate property. Writing each row directly to a destination while parsing can leave a partial export when a later row fails. For a modest file, validate all rows before writing. For larger data, write a temporary file, flush and close it, and replace the destination only after success. The precise durability guarantees depend on the filesystem; a successful rename should not be described as a complete backup or distributed transaction.

Worked problem A CSV export has three valid records followed by an amount field containing twelve dollars. The destination already contains yesterday’s valid report. Design failure behavior that preserves it.

Step-by-step reasoning 1. Use the CSV parser for quoting and column boundaries. The invalid amount can be identified as a numeric/domain conversion failure at its actual row, rather than a CSV quoting failure.

  1. Do not truncate yesterday’s file before validation. Either accumulate validated records or direct output to a separate temporary path.
  1. If conversion fails, discard the temporary output and return a useful error. Yesterday’s report remains the published destination.
  1. On success, close the output and replace the destination through the platform’s documented mechanism. Test the failure path explicitly, not only the happy path.

Failure-oriented laboratory: Atomic export and failure recovery

A successful calculation and a successful export are different events. If a process truncates the previous report before validating the new input, a later parse error can destroy the last useful artifact. Separate a pure transformation from input validation and output replacement. Validate all rows first; write the complete candidate to a temporary file in the destination directory; flush and close it; then replace the destination. A same-filesystem replacement can provide an atomic name change on supported local filesystems, but it is not a complete durability or distributed-storage guarantee.

The failure contract needs tests, not just a happy-path example. Preserve a sentinel previous report, supply an invalid late row and assert that the sentinel remains byte-for-byte unchanged. Also test a conflicting repeated event ID: identical retries may be idempotent under the chosen contract, but different events with equal values are not duplicates. An event ID repeated with changed contents should be rejected rather than silently ignored.

Use only a temporary directory and synthetic data. Inject failures at validation and immediately before replacement. Compare the observed filesystem after each failure with the documented contract. Then explain which guarantees depend on local filesystem behavior and which are established by the pure calculation tests.

Worked fixture

A synthetic ledger contains event A +100 cents, event B +100 cents and an identical retry of A. The export then encounters an invalid amount on the last row.

Explain the fixture

With event-ID idempotency, the accepted events total 200 cents before the invalid row. A policy that rejects the entire input should publish no new report, retaining the previous valid report. Deduplicating by amount would incorrectly drop B; publishing a partial total would violate the all-or-nothing input contract.

Integrated application: implementation, debugging and local deployment

The complete service-company project is now part of this unit’s applied work. It supplies an inspectable browser interface, HTTP server, persistent SQLite ledger, transaction tests, export recovery, permission-scoped retrieval and a separate synthetic logistic evaluation pipeline. Begin with its actual test suite, then trace one user request from UI to storage and back. The README distinguishes the local teaching environment from a production deployment.

Course-specific investigation

Trace validated integer-cent events from browser input to database and CSV. Add a full-file CSV importer that validates every row before committing anything. Test a bad last row, an identical retry, equal-value distinct events and conflicting IDs.

What the evidence must establish

Preserve the last valid export when any pre-replacement failure occurs. Reconcile event IDs, amounts, row counts and the recorded version; passing a string-format test alone does not establish ledger correctness.

Keep a reproducibility log with Python version, launch command, fixture, expected result, observed result and explanation of any discrepancy. Introduce one deliberate defect and show the corresponding failing test before restoring the implementation. Passing an existing test without explaining its boundary is insufficient. The integration project remains optional practice rather than a mandatory capstone submission.

Turn a file example into a stated boundary

The retained read_amounts example demonstrates quoted fields and integer conversion. It is not a complete customer-record validator. It currently accepts a third field without inspecting it and accepts a blank customer; int also accepts spellings such as +1, surrounding spaces and some non-ASCII digits. Whether those spellings are permitted is a contract decision. The new read_validated_amounts laboratory deliberately chooses a stricter contract, rather than implying that merely calling DictReader validates every record.

Its header must be exactly customer,cents in that order. Each data record has exactly two fields. A customer must contain some non-whitespace text and have at most80 code points; its spelling is preserved without trimming. The amount is an optional minus sign followed by either zero or an ASCII nonzero digit and further ASCII digits. It has at most13 digits and absolute value at most10**12 cents. Refunds and zero are valid; +1, 01, whitespace-padded amounts, fractions and non-ASCII digit spellings are rejected. The complete decoded teaching input is limited to10000 UTF-8 bytes. This small parser returns a list after complete validation, so its memory use grows with the input. It is not the later large-file design.

Use csv.reader with the selected dialect and strict=True, and separately check field counts and domain rules. The strict option makes particular malformed quoting fail; it does not define every possible CSV convention or replace schema validation. A syntactically parsed row can still have the wrong number of fields or an invalid customer. The earlier corrected ledger companion remains the event/customer/amount parser for the course's separate three-column performance study; these two interfaces should not be mixed without an explicit conversion.

Logical records are not physical lines

CSV quoting permits a field to contain a newline. With the text customer,cents followed by a quoted customer spanning the next two physical lines, the following bad record is the third logical record including the header but ends on physical line4. enumerate(reader,start=2) counts logical records; labelling that counter as a physical line misdirects the learner. The new BoundaryError records both the logical record ordinal and reader.line_num, which reports the physical line at the end of the parsed record. It does not claim that an ending-line number is always the location of the precise offending character.

For the actual fixture 'customer,cents\n"Ada\nInc",500\nBad,x\n', record2 ends on physical line3 and is valid. Record3 ends on line4 and fails the chosen amount grammar. The previous tiny parser reports line3 because it counts records. The new parser reports record3, ending physical line4. A broken quoted header is record1, rather than record2; a separate test protects that first-record boundary. CSV syntax failures retain their csv.Error cause, while a domain-rule failure is a distinct BoundaryError. This preserves the distinction between parsing and validation in executable behavior.

Reading, decoding and closing are different operations

The complete beginner Files chapter uses useful small filters and copying examples. Apply several qualifications when extending them. Relative paths resolve from the process's working directory, which need not be the directory containing the script. Mode w truncates an existing file when it is opened, even if no write follows. The plus sign modifies a base mode such as r+; '+' by itself is not a valid mode. A path such as /usr/share/dict/words is an example, not a promised file on every Unix installation. Platform rules for separators differ; a backslash is a separator on Windows but can be an ordinary filename character on POSIX systems.

readline returns a blank line as '\n' and end of input as ''. The last nonempty line need not end with a newline, so the source's 'always includes' wording is too strong. The synthetic stream '\nlast' yields '\n', then 'last', then ''. Those observations explain why a blank line is not the end marker. Reading a whole file or all lines materializes it; iterating lines avoids that particular allocation, but one unusually large record or an ever-growing identity map can still consume substantial memory.

For bytes, str(raw) gives a representation such as the visible b-prefix and escape sequences, not decoded text. Use raw.decode with the chosen encoding and error policy. The source's web example therefore does not perform the promised text decoding merely by wrapping returned bytes in str. Prefer the public response read interface, a context manager, a timeout and a bounded byte policy when writing an actual retrieval function. The offline laboratory needs no historical network endpoint: it demonstrates UTF-8 decoding and an invalid-byte failure directly. Ignoring decoding errors would silently discard information and is a different contract.

The current assigned reference snapshot describes a UTF-8 default. In the tested Python3.12 environment, text defaults can depend on locale/UTF-8 mode; an explicit non-UTF8 locale was reproduced. Specify encoding='utf-8' when UTF-8 is the chosen representation, and newline='' for CSV files so the CSV module controls embedded/newline handling. Closing and flushing make resource state observable; they do not establish every storage durability property.

Handle the failure that actually occurred

The beginner Exceptions chapter's bare except catches more than a bad filename or exhausted recursion. It can catch KeyboardInterrupt and SystemExit, concealing a user's intended termination. A failed open can also mean a permission problem rather than an absent file. Choose the narrow exception type at the operation whose failure you understand. A path existence test is not a guarantee that a later open will succeed: the filesystem can change between those observations. Perform the needed operation and handle its actual result.

In the turtle cleanup example, win is assigned only after resource construction succeeds. If that construction fails, finally: win.bye() tries to use an unbound local and reports UnboundLocalError, masking the original acquisition error in the active exception. The new non-GUI fixture reproduces this with a deliberately failing resource constructor. A with acquire() block never enters its body if acquisition fails; an entered context's exit method can then perform its documented cleanup for a later body failure. If __enter__ itself partly acquires resources and fails, it is responsible for its own partial cleanup. Cleanup can also fail; inspect chained context rather than assuming the final reported error was the first failure.

Finally does not mean successful completion, rollback or survival of process termination/power loss. A return in finally can suppress an exception or override a return value. Prefer cleanup without a control-flow return. The newer reference's unparenthesized multi-exception syntax does not compile on the tested3.12 interpreter; use except (RuntimeError,TypeError,NameError): for that version. The earlier explanation of exception chaining, else scope, exception groups and notes remains part of the complete assigned study; inspect which failures propagate rather than catching every exception and returning a monetary zero.

Bound memory without abandoning event identity

The earlier changed-case solution's streaming output and small counters are sufficient only when no other state grows with distinct records. Under the separate global event-ID contract, a seen dictionary retains one payload for every distinct ID, so Python memory grows with U unique events. Sampling old identities or forgetting them cannot preserve arbitrary later identical/conflicting retry checks. Either change the contract explicitly or move the identity state to an external index or external sorting process. The index still exists; its storage did not disappear because the output is streamed.

The new disk_total receives an iterator of pairs (event_id,cents). Its ID is exact UTF-8-encodable text of length1..80 code points, with no implicit normalization; cents is a built-in int excluding bool, with absolute value at most10**12. A private temporary SQLite table maps each ID to its accepted amount. Parameterized lookups distinguish an absent ID, an identical retry and a changed amount under an existing ID. A new ID adds once, an identical retry adds nothing, and a conflict rejects the batch. The invariant after each accepted prefix is that the index has precisely its distinct identity/payload pairs and total is their sum. Successful exhaustion establishes the full-batch result; a failed iterator or validation cannot justify publishing a prefix as complete.

The implementation retains the current bounded-size record and counters rather than a Python map of all IDs, and stores O(U) identity state on disk. Indexed lookups add database work; they are not free constant-time operations. Integer counters/totals also need more bits as the stream grows. SQLite cache configuration reduces a source of growth but is not an independently measured hard resident-memory bound for every database/interpreter implementation. A real deployment needs field limits, disk quotas, failure policy and measurement in its target environment. The executable generator fixture delivers5000 distinct events twice each and checks its result against the independent arithmetic-series total n*(n-1)/2; it is not a claim that ten million records were benchmarked.

This index is private and disposable. Committing batches of its rows limits a transaction's footprint without publishing an incomplete business ledger. Each invocation reconstructs a total from its supplied batch. Replaying the same full batch gives the same report; that is not a claim of durable idempotence across arbitrarily different future imports. A persistent production ledger needs a separate transaction and identity-lifetime contract.

Publish a complete candidate and test failure paths

export_disk_total first finishes the disk-index calculation. Only then does it write a same-directory temporary candidate, flush, fsync the file, close it and call os.replace. The existing report is not opened with w during validation. A bad late value, a conflicting ID, an injected pre-replacement error and a simulated replacement denial must each leave the previous report unchanged. The tests inspect exact destination bytes and temporary cleanup, then verify a valid180-cent result and the same result on replay.

os.replace can replace an existing file with permission and may fail across filesystems. A successful atomic name change does not choose between competing writers, prove that the upstream source was complete or guarantee power-loss recovery of all file/directory metadata. File fsync is not a complete multi-file or distributed transaction. The laboratory deliberately makes those limits part of the explanation; additional guarantees need additional mechanisms and experiments.

Validate JSON behavior and interpreter capability

Parsing JSON is not schema validation. Python's default decoder accepts repeated object names with the last value winning and accepts nonfinite token extensions. strict_json uses object_pairs_hook to reject repeated names, parse_constant to reject NaN/Infinity tokens, and a finite-result float parser to reject overflow such as1e400. The last case matters because it is valid numeric syntax and does not pass through parse_constant. Its size limit is a small teaching boundary, not a complete adversarial resource guarantee. Valid JSON true remains a bool; an integer-cents schema must separately reject it with the appropriate type rule. Consecutive JSON documents are not one framed JSON document, so repeated dump calls need a chosen framing format or an enclosing collection.

The mapped snapshot's array_hook/frozendict examples require newer Python features, and python -m json was added later than the tested3.12 interpreter. Use python -m json.tool there and do not pass array_hook to its decoder. Likewise the modern CSV snapshot's QUOTE_NOTNULL/QUOTE_STRINGS reader description does not describe3.12's known bug: empty unquoted fields were reproduced as empty strings rather than None, matching the versioned primary documentation's notice of a3.13 fix. Feature names alone do not establish their behavior on an installed interpreter.

An exact large Python integer may also change when converted to an IEEE754 double-precision float. The laboratory demonstrates that with2**53+1. If an ID must survive consumers with that numerical representation, a string ID and an explicit schema can preserve its digits; JSON's successful parsing in one Python process does not establish every consumer's numeric fidelity.

Independent changed record with complete rules

Use the two-column grammar above and the exact input 'customer,cents\n"Ada\nInc",500\nBad,x\n'. Count the header as logical record1; reader.line_num reports the ending physical line. State the failing logical record and physical line, and explain why substituting0 for x violates the all-or-nothing parser contract. Predict the result for a third field and for a blank customer under these chosen rules. Then decode UTF-8 bytes for 'café' and contrast that result with str applied to those bytes.

For the separate event-index interface, process [('A',100),('B',100),('A',100),('C',-20)]. IDs are exact UTF-8 text, identical ID/amount retries are ignored and changed amounts under an existing ID reject the whole batch. The destination initially contains the bytes 'previous valid report\n'. Predict its bytes after a valid run, after a late ('D','bad') row, after ('A',101), and after an injected pre-replacement failure. Each run begins again with the stated sentinel for the failure comparisons. Explain why two distinct equal100-cent events contribute twice and why global conflict checks require identity storage even when output is streamed. Finally predict strict_json for '{"id":"A","cents":100,"cents":101}', '1e400' and 'true'. State which observations concern parsing and which require a further domain rule. Produce your reasoning before opening the complete solution; all practice remains optional.

Integrated CSV import: validate first, commit once

The complete application now has an original importer that joins this unit's file boundary to its actual tenant-scoped SQLite ledger. The selected file contract is exact: UTF-8; at most 1,000,000 bytes and 10,000 data records; header event_id,cents; exactly two fields; an exact, non-normalized ID of 1–80 code points; and integer cents spelled with an optional minus followed by zero or a nonzero ASCII digit and further ASCII digits, with absolute value at most 100,000,000. Plus signs, leading zeroes, surrounding whitespace, fractions, non-ASCII digits, extra fields and malformed quoting are rejected. These are application choices, not automatic CSV guarantees.

The importer validates the entire file and reconciles repeated identities inside it before starting a write transaction. Distinct IDs with equal amounts remain distinct events. An identical ID/amount is a retry; a changed amount under the same ID is a conflict. Logical record ordinals and the parser's ending physical line are retained for diagnosis. Because this teaching interface materializes the validated batch, explicit byte/record bounds are part of its memory contract.

Persistent reconciliation then occurs inside one BEGIN IMMEDIATE transaction. Every lookup uses tenant and event ID. An absent ID is new, an identical stored amount is a replay, and a changed stored amount rejects the whole batch. A batch with any new event requires the current expected version. A batch containing only exact replays is safe with a stale pre-commit version. Every new event row, non-null audit row and version increment is committed together; any exception rolls them all back.

Worked trace: from tenant A version0, deliveries A100, B100, A100 contain three deliveries, two unique events and one within-batch retry. Both A and B are new, so the transaction writes two events and two audits and advances to version2 with total200. Repeating the same file with expected version0 changes nothing: both unique IDs are persistent replays, so version2 and total200 remain. Changing the final A to101 fails before the transaction; changing an A already in the database fails inside the transaction. An injected null audit message after event inserts proves rollback of events, audits and version, not merely rejection of an invalid file.

Run the eight published groups against the complete application source. They check a bad last row, exact grammar and multiline diagnostics, equal-value distinct events, identical retries, conflicts in both phases, tenant isolation, stale versions and an audit failure after persistent work begins. These local tests do not establish distributed transactions, production authentication, every crash-durability mode or resource resistance beyond the stated limits.

Apply the idea

A CSV export has three valid records followed by an amount field containing twelve dollars. The destination already contains yesterday’s valid report. Design failure behavior that preserves it.

A file has ten million rows, so keeping every record in memory is impractical. Propose a bounded-memory design and identify one failure that atomic replacement does not solve.

Additional laboratory — Implement two failure-injection tests and a conflict test for A repeated with +101 cents. Add a successful-run test that replaces the sentinel only after complete validation.

Complete-application investigation: Trace validated integer-cent events from browser input to database and CSV. Add a full-file CSV importer that validates every row before committing anything. Test a bad last row, an identical retry, equal-value distinct events and conflicting IDs.

Further independent boundary record

Standalone input rules: require exactly the header customer,cents and exactly two fields per data record. Customer is nonblank and at most80 code points, preserved without trimming. Cents is an optional minus followed by either0 or an ASCII nonzero digit and ASCII digits, at most13 digits and absolute value at most10**12; refunds and zero are allowed, plus signs/leading zeros/whitespace/non-ASCII digits are rejected. The small parser validates the full input before returning a list. The report procedure validates the complete event batch using its exact-ID index, writes the decimal total followed by a newline to a separate same-directory candidate, flushes and closes it, then replaces the destination only after success. No partial result is a completed report. For strict_json, reject duplicate object names, NaN/Infinity token extensions and any float conversion giving a nonfinite result; otherwise use ordinary JSON parsing with schema validation still separate.

Use the two-column grammar above and the exact input 'customer,cents\n"Ada\nInc",500\nBad,x\n'. Count the header as logical record1; reader.line_num reports the ending physical line. State the failing logical record and physical line, and explain why substituting0 for x violates the all-or-nothing parser contract. Predict the result for a third field and for a blank customer under these chosen rules. Then decode UTF-8 bytes for 'café' and contrast that result with str applied to those bytes.

For the separate event-index interface, process [('A',100),('B',100),('A',100),('C',-20)]. IDs are exact UTF-8 text, identical ID/amount retries are ignored and changed amounts under an existing ID reject the whole batch. The destination initially contains the bytes 'previous valid report\n'. Predict its bytes after a valid run, after a late ('D','bad') row, after ('A',101), and after an injected pre-replacement failure. Each run begins again with the stated sentinel for the failure comparisons. Explain why two distinct equal100-cent events contribute twice and why global conflict checks require identity storage even when output is streamed. Finally predict strict_json for '{"id":"A","cents":100,"cents":101}', '1e400' and 'true'. State which observations concern parsing and which require a further domain rule. Produce your reasoning before opening the complete solution; all practice remains optional.

Integrated transfer — Use tenant A version4 with stored event A100. Import B100, A100, B100 at expected version4. Derive the resulting version, total contribution, new-event count, persistent-replay count and within-batch-retry count. Repeat the same file with the old expected version and explain why no state changes. Then change the last B to101 and identify whether phase-one or transactional reconciliation rejects it. Finally explain why tenant B's A700 does not conflict with tenant A's A100. Add audit-failure injections on the first and second new events and prove both leave the same pre-transaction state.

Read the worked reasoning

Stream parsed, validated rows into a temporary output while retaining only counters and a small error sample. Commit the output after the complete input validates, or use an explicit partial-acceptance report if that is the chosen contract. Atomic replacement does not prove the input was complete, protect against a corrupted backup, or coordinate concurrent writers. Add a run identifier and a policy for writer ownership or version conflicts.

Additional laboratory model — Both injected failures must preserve the sentinel. The conflicting ID must raise a documented validation error and leave output unchanged. A valid run must produce exactly 200 cents, and replaying the same input must not double the result. Report the tested local environment; do not claim these tests prove cross-machine crash durability.

Application reasoning model: Preserve the last valid export when any pre-replacement failure occurs. Reconcile event IDs, amounts, row counts and the recorded version; passing a string-format test alone does not establish ledger correctness.

Further boundary reasoning

The quoted customer occupies physical lines2 and3 but is one CSV record, logical record2. The malformed amount x is in logical record3, ending physical line4. The selected grammar rejects it and returns no completed list. Replacing x with0 would invent a successful value and conceal a rejected input. A third field violates the exact two-field rule and a blank customer violates the nonblank-customer rule. These are explicit choices of the new boundary, not facts supplied automatically by CSV parsing. UTF-8 decoding returns café; str(bytes) instead displays a bytes representation including a b-prefix and escapes.

The four event deliveries represent distinct IDs A,B,C. Their accepted amounts sum100+100-20=180; the identical A retry contributes nothing. A successful export contains exactly the UTF-8 bytes '180\n'. Under each separately reset failure comparison the destination remains 'previous valid report\n': a bad late type, conflicting A amount or pre-replacement exception prevents publication of a complete candidate. A successful retry of the same full batch again produces180; it does not add180 to an existing report. Distinct IDs A andB remain distinct despite equal amounts. A global identity map grows with distinct IDs; a disk index retains those identities externally, while a pure line-by-line counter cannot detect every later conflicting reuse.

The duplicate cents JSON names are rejected before the result can become an ordinary mapping. The numeric token1e400 is rejected because the chosen float result would be nonfinite; parse_constant alone would not catch that overflow. JSON true successfully parses as bool, but that does not satisfy the event interface's built-in-int cents rule. File resource cleanup and atomic replacement do not decide among competing writers or establish power-loss recovery; their guarantees require separate contracts and tests.

Integrated transfer reasoning — B is one new event, A is one persistent replay, and the second B is one within-batch retry. The version advances from4 to5 and B contributes100 once. Repeating after success finds A andB as persistent replays; with no new event, the stale pre-commit expected version is safe and version5 remains. If two B deliveries disagree, full-file reconciliation rejects before BEGIN IMMEDIATE. A conflict with an ID already stored is discovered inside the transaction and rolls back. Identity queries include WHERE tenant=? AND event_id=?, so tenant B's A cannot answer tenant A's lookup. A null audit message raises after inserts have begun, and the context manager rolls back all events, audits and the version increment. Serial rollback tests do not establish which of two simultaneous writers waits or wins; that needs a concurrent-writer experiment and timing contract.

Check understanding

Why is except Exception: return 0 dangerous here?

  1. It makes a failed parse look like a successful zero amount
    Feedback

    Failure and a valid monetary value become indistinguishable.

  2. It guarantees every input is validated
    Feedback

    Swallowing errors removes validation evidence.

  3. It ensures files are never overwritten
    Feedback

    Exception handling alone imposes no write-safety policy.

Further reading

Current study directions: the original Academy lessons, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters and their historical reading directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending.

Use the original worked investigations and optional changed-record models in this unit. Historical directions below are retained as source history and do not require publisher chapters.

My learning →