Lawfare Academy

CS 101 — Programming Foundations with Python · Weeks 15–16

Modules, reproducibility and an integrated estimator

Full teaching sequence and cumulative subject work

Read modules and object basics before integrating the estimator. Compare a function-based design with a small class that preserves a stated invariant. Work the recursion examples with explicit base cases and trace the call stack. Advanced GUI and later data-structure chapters remain optional extensions. 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 →

A reproducible command-line pipeline

An integrated program should make data flow and failure behavior visible. The entry point reads configuration and arguments, calls parsing and validation, computes the result, and exports a documented format. Pure functions should not silently depend on the current working directory or print intermediate output. A command-line program can return an exit status while a reusable function returns a structured result.

Reproducibility requires more than setting a random seed. Record the input version, program version, policy choices and dependencies. Avoid including unnecessary personal data in diagnostics. A run identifier can connect a summary to its source without embedding the entire source file in logs.

Worked problem

Design a work-order estimator that can be imported in a test, run from a terminal, and retried after export failure without charging a customer twice.

Trace the complete reasoning
  1. Keep estimate(records, policy) pure: it returns totals and validation findings without performing payments or printing.

  2. Put argument parsing and process exit behavior behind the script entry-point guard. Importing the module must not launch a run.

  3. Write a result manifest with input checksum, policy identifier, output format and program version. Export retry is a separate operation from any payment workflow.

  4. If a payment action is later added, use a stable operation key and durable action ledger. Rerunning a calculation does not itself establish idempotent payment behavior.

Independent transfer problem

A run succeeds on one machine but reads a different rates.csv on another. Explain the likely dependency and redesign the invocation so the discrepancy is diagnosable.

Compare the transfer solution

A relative filename may have resolved against different working directories. Require an explicit input path or a documented configuration root, resolve and report the chosen source, and include its checksum in the manifest. Keep the report free of unnecessary confidential paths if shared publicly. Tests should run from a temporary working directory to reveal hidden filesystem assumptions.

Learning objectives

  • Explain and trace the mechanisms in modules, reproducibility and an integrated estimator.
  • 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

A useful application separates its domain rules, input adapters and user interface. Place estimate and aggregation functions in an importable module; put command-line interaction behind a main entry point. Importing a calculation module should not prompt for input or overwrite files. This separation lets tests load the rules without starting the application.

Reproducibility means another person can recreate the execution conditions and obtain a justified result. Record the Python version, dependency versions, input format and commands. A virtual environment isolates project packages from other projects, but is not a security boundary. If the program uses only the standard library, say so; do not add dependencies simply to appear sophisticated. When a library is needed, verify its maintained documentation and record compatible versions rather than installing arbitrary packages with similar names.

Integration tests exercise a workflow across boundaries: parse a fictional CSV, validate it, calculate totals, produce output and read that output back. Include an invalid batch and confirm that it leaves no misleading success artifact. An operational README should state what the tool handles and what remains out of scope. Evaluate change requests through those boundaries. Supporting fractional hours requires a representation and rounding decision; supporting multiple currencies requires currency-aware aggregation; supporting several users requires identity, authorization and concurrency design. A small coherent program is a better result than a larger program whose output cannot be explained.

Worked example

def summarize(records):
    return {"transactions": len(records),
            "net_cents": sum(cents for _, cents in records)}

def main():
    result = summarize([("Job A", 18750), ("Refund", -2500)])
    print(result)

if __name__ == "__main__":
    main()

Running the file prints a two-field summary with transactions 2 and net_cents 16250. Importing it defines the functions without printing. The guard separates execution as a script from reuse as a module. The function receives already validated records; a real coordinator must call the parser first. The output is a Python dictionary representation, so a portable file export should instead choose a documented format such as JSON or CSV.

Check your understanding

Why put interactive behavior behind a main guard?

  1. So importing reusable functions does not unexpectedly run the interface
  2. So type hints become enforced
  3. So dependency versions are automatically recorded
Answer and reasoning for every option

Correct: So importing reusable functions does not unexpectedly run the interface Import-time side effects make reuse and tests harder.

Reconsider: So type hints become enforced The guard does not perform runtime type validation.

Reconsider: So dependency versions are automatically recorded Reproducibility needs explicit environment documentation.

Transfer laboratory: A new hourly representation

Extend the estimator from integer hours to integer minutes at 6250 cents/hour. A 35-minute job must round to the nearest cent, with half cents rounded upward. Explain the exact result and policy.

Work through the full solution

Calculate 6250×35/60 = 3645.833… cents, which rounds to 3646. Use integer rational arithmetic or Decimal under an explicit rounding rule; do not silently convert minutes to rounded hours first. State whether each line is rounded before summing or the invoice is rounded once, because these can differ. Test 0, 1, 35 and 60 minutes and reject negative minutes.

Evidence of understanding

Preserve units, compute 3646 cents and test a case where line-versus-invoice rounding differs.

Complete on-site teaching readings

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

  1. 12. Virtual Environments and Packages · Python Software Foundation and Python documentation contributors
  2. 10. Brief tour of the standard library · Python Software Foundation and Python documentation contributors
  3. 11. Brief tour of the standard library — part II · Python Software Foundation and Python documentation contributors
  4. logging — Logging facility for Python · Python Software Foundation and Python documentation contributors
  5. argparse — Parser for command-line options, arguments and subcommands · Python Software Foundation and Python documentation contributors

Open in My Learning to record progress →