Function Contracts, Binding and Ownership

Original worked explanation, source corrections and optional independent experiments. Review the retained complete source chapter alongside the native lesson.

Read the Functions source with an executable contract

The complete assigned Functions chapter develops decomposition, parameter binding, calls, results and turtle-based composition. Retain those examples and their figures, and apply these corrections when running them. In section 4.5, final_amt_v3 declares compounded but uses the misspelled componded in its exponent. In a fresh environment the call raises NameError. Change that reference to compounded; changing the caller's variable name does not repair a misspelled name inside the function. The original names remain visible in the retained source so the discrepancy can be located exactly.

The same section assigns toInvest=float(input(...)). input returns text, then float converts it; after that complete assignment toInvest refers to a float, rather than the string described by the surrounding prose. Follow the nested calls from the inside out. For the synthetic input text '10000', input first supplies that string, float produces 10000.0, and assignment binds the caller's name to the float. When a function is called, its parameter name receives a reference to the supplied argument object. The parameter and caller names need not be spelled alike.

The source's arithmetic example illustrates a formula, not a complete money-record specification. Binary floating-point operations already incur rounding; printing two decimal places controls presentation and does not restore exact decimal information. The earlier exact-money laboratory remains the course's representation study. For the separate synthetic formula here, the new laboratory accepts nonnegative int or Fraction principal/rate values, excluding bool, a positive built-in integer number of periods per year, and a nonnegative built-in integer number of years. A rate of one tenth means 10 percent, not the integer ten. These are explicit mathematical experiment rules, not a prediction or recommendation about an investment.

Derive the recurrence before comparing renamed functions

Let p be the starting amount, r the annual fractional rate, n the periods per year and t the whole years. There are N=n*t updates and each update multiplies the current amount by f=1+r/n. The recurrence starts A0=p and uses A(k+1)=Ak*f. Induction gives Ak=p*f**k: it holds at zero, and multiplying the induction hypothesis by f gives the next case. At N updates the result is p*(1+r/n)**(n*t). The finite loop has the decreasing measure N-k. This argument establishes what the calculation means under the stated exact rational contract; a variable rename preserves it only if every reference and parameter binding is changed consistently.

For p=100, r=1/10, n=2 and t=1, the factor is 21/20. The trace is 100,105,441/4, so the final amount is exactly 110.25. With n=1, the factor is 11/10 and there is one update, giving 110. With t=0 there are zero updates and the result is the original 100. Changing a denominator or exponent while renaming parameters changes the calculation. The laboratory compares a multiplication loop with an independently expressed closed form over several exact records, including zero-time and zero-rate cases.

Distinguish a local name from the lifetime of its object

A function-local name is ordinarily unavailable through a global lookup after the call. That does not imply that every object used by the function is destroyed when it returns. A returned object can remain reachable through the caller's binding. The source's functions that return turtles already illustrate this distinction: a locally named turtle can be returned and used by the caller. Its object lifetime differs from the visibility of the function's ordinary local name.

The complete make_report example sets local_rows=list(rows) and returns {'orders':local_rows}. With source=['A'], make_report(source) gives a new outer list in report['orders']. Appending 'B' to source and 'C' to the report leaves source=['A','B'] and the report list=['A','C']. The list returned through the dictionary remains usable after make_report has returned. If another dictionary is created with report.copy(), it shares that report list: appending 'D' through the second dictionary also changes the first report's list. Distinguish the identity of the outer dictionaries from the identity of their nested value.

Now change the original input to [[1]]. list(rows) copies the outer list but retains a reference to the same inner list. Appending 2 to report['orders'][0] therefore changes the original input to [[1,2]]. This does not contradict the earlier flat-string example. The operation protected the outer list only; mutable nesting changed the ownership boundary that matters. State whether nested sharing is intended before choosing a deeper copy or an immutable representation.

Definition-time work, call-time work and retained state

Defining a function creates and binds a function object without running its body. Some expressions attached to the definition can still run then. A default argument is evaluated when the definition executes. If it produces a list, later calls using that default share the same list. The laboratory records 'default evaluated' once and 'body called' separately on each of two calls. Its remember function instead uses a None default and creates a new list inside for calls that omit an existing list. An explicitly supplied list is intentionally reused; a default policy should not conceal a different ownership policy for supplied arguments.

As a further lifetime example, make_counter creates count=0 and returns an inner increment function. The returned function uses nonlocal count to update the retained enclosing binding. Calling the outer function twice creates two separate enclosing bindings. Calls first(),first(),second(),first() return 1,2,1,3. Without nonlocal, an assignment to count inside increment would create a different local binding, and count+=1 would try to read that local before it was assigned. This explanation concerns lexical scope and retained references; it does not turn every local name into a global.

An effect and a returned value are also separate observations. A function that appends 'C' to a supplied list and reaches its end returns None. The list can change even though the returned value is None. The chapter's term void describes a function used for its effect; Python still supplies a return value. Inspect both the result and the permitted effects when testing a contract. The historical PyScripter debugger controls and __traceable__ setting in the source are editor-specific conveniences; understanding parameter and call traces does not require that editor or setting.

Independent changed record

Use the exact recurrence contract p=100, r=1/10, n=2, t=1 and derive every amount, then change n to 1 and t to 0 separately. Identify the failure when a function declares compounded but evaluates componded, and identify the resulting type of float('10000'). For make_report(rows), the full rule is local_rows=list(rows), followed by returning {'orders':local_rows}. With source=['A'], obtain report, append 'B' to source and 'C' to report['orders'], then make outer=report.copy() and append 'D' through outer['orders']. State every final list and which objects are shared. Repeat with source=[[1]] and append 2 through report['orders'][0]. Finally explain why two make_counter factories, each starting count=0 and returning a nonlocal increment function, produce 1,2,1,3 under first(),first(),second(),first(). Explain the contracts before comparing with the complete source; all practice is optional.

Compare the complete changed-record reasoning

For the exact two-period recurrence the amounts are 100,105,441/4. Changing to one annual period gives 110; changing to zero years gives 100. The misspelled componded is an unbound name in the isolated function and raises NameError; the minimal repair uses the declared compounded consistently. float('10000') returns a float with value10000.0. In the flat list record, source ends ['A','B']; report['orders'] and outer['orders'] both end ['A','C','D'] and refer to the same list, while the dictionaries themselves are distinct. In the nested record the copied outer lists differ, but both index0 values refer to the same inner list, so the original becomes [[1,2]]. Returned objects remain reachable after a function call even though its ordinary local name is not a global. Each counter factory creates a separate enclosing count binding; the first increment function retains and changes its own binding three times, while the second changes its own binding once. nonlocal selects that enclosing binding for assignment. These traces explain the observed results rather than attributing them to caller variable spelling or assuming every copy provides deep isolation.

Run the complete laboratory

Save as function_contracts.py and run python function_contracts.py. Tested on Python3.12.14 with the standard library. Seven groups examine an actual source typo, conversion type, exact recurrence and its closed form, input contracts, flat/nested ownership, definition-time defaults, returned effects and independent retained closure state.

Source SHA-256: 1897ded315e13c70d2654b5157496e9defdf5674e9f3b73b16d3f7e3bc85d67d

Complete Python source and executable tests

Source locators

The complete Functions source text and eleven figures were reviewed. A turtle GUI was not executed. The other full unit3 readings and whole-course academic acceptance remain pending. No university or publisher affiliation or equivalence is claimed.