Lawfare Group → Knowledge Institute → Lawfare Academy
← CS 101 — Programming Foundations with Python
Weeks 15–16
Modules, reproducibility and an integrated estimator
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.
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.
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 reasoning 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.
Extended teaching and laboratory
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.
Step-by-step reasoning 1. Keep estimate(records, policy) pure: it returns totals and validation findings without performing payments or printing.
- Put argument parsing and process exit behavior behind the script entry-point guard. Importing the module must not launch a run.
- Write a result manifest with input checksum, policy identifier, output format and program version. Export retry is a separate operation from any payment workflow.
- 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.
From a repeatable command to a reproducible result
A command line by itself is not a complete experiment. The result depends on the exact input bytes, program and interpreter behavior, and policy choices such as rounding. Record explicit input paths, SHA-256 digests, program and interpreter versions, the policy identifier and the rounding boundary. Identical totals do not prove identical inputs. A digest supports byte identity under its hash assumptions; it does not establish that a source was authorized, accurate or complete.
Separate reusable rules from process behavior. Parsing converts exact input contracts into records. Estimation accepts validated values and returns a result. A coordinator reads explicitly supplied paths and publishes a completed document. The command-line adapter owns argparse, stdout, stderr and process status, while the main guard prevents that adapter from running on import. A useful import test starts a fresh process in an empty working directory and requires no output or created files.
For 6,250 cents per hour and 35 minutes, the exact numerator is 218,750 cent-minutes and the denominator is 60. The result is 3,645 remainder 50, so invoice-level half-up gives 3,646 cents. With two 30-minute lines at one cent per hour, separately rounding each half-cent line gives two cents, while summing first gives one. Both traces are arithmetically sound under different policies; only the declared boundary chooses the application's answer.
Atomic local publication is a bounded claim. Construct a complete candidate beside the destination, write and flush it, synchronize the file, and only then replace the destination name. An injected replacement failure must preserve the previous bytes and remove the candidate. This does not coordinate two publishers, prove directory-entry durability after every crash or make an external payment idempotent. A future external action needs a stable operation key, durable action states and reconciliation after ambiguous responses.
The complete integrated-application companion exercises the cumulative path rather than merely describing it. Its real HTTP routes enforce tenant identity before retrieval, SQLite commits ledger/version/audit changes together, exact retries are idempotent while conflicts and stale writes are rejected, exports replace only complete candidates, and the separate model pipeline fits preprocessing on training data, selects on development data and reports held-out counts. Its README explicitly limits the supplied server to local synthetic study and identifies authentication, transport, operational and database work that production would require.
Objects that own a state invariant
A class defines a type; calling it creates an instance and invokes its initialization method. An instance attribute belongs to that particular object. A method combines a function with an instance: `a.book(20)` supplies `a` as the first argument named `self`. That name is a convention rather than a special keyword. Two names can refer to one instance, so changing the object through one name is visible through the other. Creating two instances instead gives two separate sets of instance attributes.
Use a class when an operation must maintain related state through several calls. Pure functions remain a good choice for independent calculations. Consider a synthetic nonnegative work budget, with integer minutes and no refunds. The invariant is `0 <= used <= limit`. Initialization establishes it, and each successful booking must preserve it. Reject a proposed booking before changing state; a failed booking must leave the object unchanged.
```python class WorkBudget: def __init__(self, limit): if type(limit) is not int: raise TypeError('integer minutes excluding bool required') if limit < 0: raise ValueError('nonnegative limit required') self._limit = limit self._used = 0
@property def remaining(self): return self._limit - self._used
def book(self, minutes): if type(minutes) is not int: raise TypeError('integer minutes excluding bool required') if minutes < 0 or minutes > self.remaining: raise ValueError('booking exceeds the remaining budget') self._used += minutes return self.remaining ```
For `a=WorkBudget(60)`, the state starts at used 0 and remaining 60. Booking 35 yields used 35 and remaining 25. Booking another 30 raises before assignment, so remaining stays 25. Booking zero succeeds without changing the invariant. Negative minutes are rejected rather than interpreted as cancellation; cancellation would require its own stated policy. The arithmetic proof is local: an accepted amount is between zero and `limit-used`, so the new used value is at least zero and at most limit.
The leading underscore signals an implementation detail. It does not enforce authorization or prevent a caller from writing `a._used=1000`. The invariant is guaranteed by the supplied interface under its assumptions, not against arbitrary modification of the object. A read-only property makes the supported observation convenient; it does not turn Python objects into security boundaries. The HTTP and database layers retain their separate validation and tenant checks.
Never put per-instance mutable state in a shared class attribute by accident. If a class body contains `visits=[]`, ordinary attribute lookup can find that same list through every instance, and `self.visits.append(...)` changes the shared object. Assign `self.visits=[]` inside initialization when each instance should own its list. This is the class version of the earlier mutable-default and shallow-copy problem. A class attribute is appropriate for deliberately shared constants, provided their mutation policy is understood.
Inheritance lets a derived class reuse and override behavior. A derived `TrainingBudget(WorkBudget)` inherits `book` and `remaining`; it can add a label without duplicating the booking rule. If it overrides initialization, `super().__init__(limit)` establishes the base invariant before it adds its own state. An override of `book` that silently permits overbooking breaks the promise a caller expects from a WorkBudget. Reuse alone is not a justification for inheritance: composition, such as a scheduler holding a WorkBudget instance, often expresses the relationship more clearly. Methods are selected using the actual object's type, so an override affects calls made through a variable referring to that derived instance.
Recursion: a smaller problem and a suspended caller
A recursive function invokes itself on a smaller problem. Correctness needs a base case, a justified relationship between the smaller answer and the requested answer, and a decreasing measure that reaches the base case on the accepted domain. Separate calls have separate local bindings. While a child call runs, its caller can remain suspended with work still to do.
```python def triangular(n): if type(n) is not int: raise TypeError('built-in integer excluding bool required') if not 0 <= n <= 100: raise ValueError('teaching domain is 0 through 100') if n == 0: return 0 return n + triangular(n - 1) ```
The requested result is the sum of integers 1 through n. At n=0 the empty sum is zero. Assuming the smaller call returns the sum through n-1, adding n gives the sum through n. The nonnegative integer n decreases by one on every recursive call, proving mathematical termination in this finite domain. Domain validation matters: allowing negative input with only the zero base case would keep moving away from zero.
For n=3 the calls descend as 3, 2, 1, 0. The frame for n=3 waits to add 3; the frame for n=2 waits to add 2; the frame for n=1 waits to add 1. The returns unwind as 0, 1, 3, 6. Returning zero at every call would terminate but fail the result contract. Printing the intermediate values is also different from returning a value that the suspended caller can use.
This implementation uses a number of calls and retained frames proportional to n; the additions also operate on integers whose bit lengths grow. Python imposes a recursion limit, and mathematical termination does not guarantee that a particular runtime has enough stack space. The small domain is an educational bound, not a proof about the stack state of every caller. Do not raise the interpreter's recursion limit as a substitute for designing an iterative traversal. An iterative equivalent starts `total=0` and adds each value in `range(1,n+1)`, retaining a fixed number of integer variables. Both should be checked against the independent formula `n*(n+1)//2`.
Recursive structure is especially useful for nested input. A tree visitor handles a leaf directly and combines results from each child subtree. The decreasing measure can be the number of nodes remaining in a finite acyclic tree. A cyclic object graph violates that premise: following a parent reference indefinitely is not a smaller-tree computation. Choose an explicit visited-identity policy or an iterative work stack when graphs and depth bounds replace the tree contract. Counting nodes, counting paths, and counting distinct reachable objects are different questions.
Optional changed-record practice and complete reasoning
Start with two separate 60-minute budgets, a and b, and an alias `same=a`. Book 35 through a and 20 through same. Predict both remaining values; then attempt a 10-minute booking through a and inspect the state after failure. Compare this with a class-level shared visits list. Finally trace triangular(4), identify its deepest base case and independently verify the result. Change the input to -1 and explain why validation belongs before recursion.
The two successful calls affect the same a object, so a and same both show 5 remaining. The separate b still has 60. The 10-minute request exceeds 5 and raises before mutation, leaving 5. A shared class-level visits list would instead be one list observable through both instances unless each instance creates its own list. For triangular(4), descent is 4,3,2,1,0 and returns are 0,1,3,6,10. The formula gives 4*5//2=10. Input -1 is rejected; it is not assigned an empty-sum answer. A changed base case or graph policy changes the specification and must be argued again.
Assess an optional response on four equally weighted criteria: correct state/alias trace; a preservation argument including failed operations; a complete call-and-return trace with base case and decreasing measure; and a justified choice of iteration or recursion that states resource and graph assumptions. Full credit requires mechanisms and changed facts, not only the final numbers.
Optional references: Python 3.12 tutorial, Classes; Python 3.12 sys recursion-limit documentation. The original on-site explanation above supplies the required introductory teaching; the retained publisher/reference chapters provide further examples. No turtle GUI or observed learner competency is claimed.
Apply the idea
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.
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.
Reproducibility transfer — Begin with STANDARD at 6,250 cents/hour and a 35-minute job. Derive the exact numerator, denominator and rounded total. Run the same explicit paths from a different current directory and explain what evidence distinguishes equal outputs from identical inputs. Then create two 30-minute lines at one cent/hour and compare line-level with invoice-level half-up rounding. Finally inject a replacement failure and state every filesystem observation required. Extend the design on paper for an external payment without treating local file replacement as payment idempotency.
Read the worked reasoning
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.
Reproducibility-transfer reasoning — 6250×35=218750 cent-minutes; 218750/60 is 3645 remainder50, so half-up gives 3646 cents. Explicit paths avoid accidental selection by current directory, while byte digests establish which files were read; equal totals alone can conceal different inputs. Two one-cent/hour half-hour lines each round to one cent if rounded separately, but their combined exact numerator60 yields one invoice cent. On injected replacement failure, the old destination bytes remain and no candidate remains; the raised exception alone is insufficient. A payment requires a stable operation key, durable action states and provider reconciliation after ambiguous responses. The present calculation deliberately performs no payment.
Check understanding
Why put interactive behavior behind a main guard?
- So type hints become enforced
Feedback
The guard does not perform runtime type validation.
- So dependency versions are automatically recorded
Feedback
Reproducibility needs explicit environment documentation.
- So importing reusable functions does not unexpectedly run the interface
Feedback
Import-time side effects make reuse and tests harder.
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.
- Original Academy — objects, invariants and recursion
- Learning with Python 3 — Modules
- Learning with Python 3 — Classes And Objects I
- Learning with Python 3 — Classes And Objects Ii
- Learning with Python 3 — Recursion
- 12. Virtual Environments and Packages
- 10. Brief tour of the standard library
- 11. Brief tour of the standard library — part II
- logging — Logging facility for Python
- argparse — Parser for command-line options, arguments and subcommands
- Original Academy — integrated computing application
- Original Academy — ledger pipeline performance study