Lawfare Academy

CS 101 — Programming Foundations with Python · Weeks 9–11

Exceptions, files and validated boundaries

Full teaching sequence and cumulative subject work

Read the complete file and exception chapters. Implement text-file processing, handle malformed records, distinguish parsing from validation and test failure after a valid prefix. Use the Academy atomic-export laboratory to connect these mechanisms. Then study the original assigned documentation as a language reference and complete the worked and transfer problems.

A complete ledger pipeline with a falsifiable specification — primary material, constructed-response tasks, complete worked model and changed-case examination →

Parsing, validation and atomic export

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.

Trace the complete 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.

  2. Do not truncate yesterday’s file before validation. Either accumulate validated records or direct output to a separate temporary path.

  3. If conversion fails, discard the temporary output and return a useful error. Yesterday’s report remains the published destination.

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

Independent transfer problem

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.

Compare the transfer solution

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.

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.

Study the mechanism

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 example

import csv
import io

def read_amounts(text):
    reader = csv.DictReader(io.StringIO(text))
    if reader.fieldnames != ["customer", "cents"]:
        raise ValueError("Expected customer,cents columns")
    result = []
    for line, row in enumerate(reader, start=2):
        try:
            result.append((row["customer"], int(row["cents"])))
        except (TypeError, ValueError) as error:
            raise ValueError(f"Invalid amount on line {line}") from error
    return result

assert read_amounts('customer,cents\n"Ada, Inc.",500\n') == [("Ada, Inc.", 500)]

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.

Check your understanding

Why is except Exception: return 0 dangerous here?

  1. It makes a failed parse look like a successful zero amount
  2. It guarantees every input is validated
  3. It ensures files are never overwritten
Answer and reasoning for every option

Correct: It makes a failed parse look like a successful zero amount Failure and a valid monetary value become indistinguishable.

Reconsider: It guarantees every input is validated Swallowing errors removes validation evidence.

Reconsider: It ensures files are never overwritten Exception handling alone imposes no write-safety policy.

Transfer laboratory: Batch reconciliation under partial rejection

Five CSV rows contain amounts 100, blank, -20, "x" and 0. The policy accepts refunds and zero while rejecting invalid amounts. Specify accepted and rejected counts and the net total.

Work through the full solution

Three rows are accepted: 100, -20 and 0; two are rejected. Net accepted amount is 80 cents. Report input count 5 = accepted 3 + rejected 2. Preserve record identifiers for correction, and do not substitute zero for blank or x because that would conceal errors and distort transaction counts. A later corrected import needs an identity policy to avoid duplicating already accepted rows.

Evidence of understanding

Reconcile every input row, preserve meaningful zero/refunds and identify a duplicate-import risk.

Complete on-site teaching readings

These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.

  1. 7. Input and output · Python Software Foundation and Python documentation contributors
  2. 8. Errors and Exceptions · Python Software Foundation and Python documentation contributors
  3. csv — CSV file reading and writing · Python Software Foundation and Python documentation contributors
  4. json — JSON encoder and decoder · Python Software Foundation and Python documentation contributors

Open in My Learning to record progress →