Binding and Scoping
Lexical Scope: Following Names to Their Declarations
Lexical scope determines which declaration a variable reference denotes by using the nesting of the program's source code. When several variables share a name, you need to identify the relevant binding before finding its value. This distinction matters when you read nested functions, return functions for later use, or debug an unexpected result. The examples here use Python function scopes.
Finding the binding
Think of an environment as a record of available names. For a variable read inside a function, first consider that function's parameters and local declarations. If the name is not local, continue through the functions that lexically enclose it, then the module. Python also checks its built-in names after module lookup.
For ordinary reads in the function-based examples here, the governing lookup idea is:
Here, E[x] denotes a binding, whose current value can then be read. The parent link follows lexical enclosure. The function's caller does not become its enclosing environment. A helper function defined elsewhere cannot supply its local variables merely by making the call.
Same spelling, different variables
Shadowing occurs when an inner declaration takes precedence over an outer declaration with the same name. The outer variable still exists; the inner declaration introduces a distinct variable.
Example: This program contains three variables named x, but the addition inside inner uses the one declared inside outer.
x = 3
def outer():
x = 14
def inner(y):
return x + y
return inner
f = outer()
def caller():
x = 100
return f(8)The parameter y supplies 8. The reference to x inside inner resolves to the enclosing function's variable, whose value is 14. Therefore, caller() returns 14+8=22. Its own x does not participate in that lookup.
Name or declaration | Role in the example |
|---|---|
Parameter y in inner | Supplies a local value for the addition |
Variable x in outer | Supplies the enclosing binding used by inner |
Variable x in the module | Is shadowed by the enclosing declaration |
Variable x in caller | Belongs to a different function and is outside the lookup chain |
Fixed lookup does not mean a frozen value
A closure can retain access to an enclosing function's variables after that enclosing call returns. This is why f can still use outer's x. The surrounding call has ended, but the binding needed by the returned function remains available.
Retaining access to a binding does not necessarily copy its value. If another function updates that same captured variable, a later read can observe the updated value. In Python, nonlocal explicitly permits such an update. An ordinary assignment inside a nested function instead creates or updates its own local variable unless another declaration changes that rule.
Each new invocation of an enclosing function can also create fresh local bindings. Two returned functions from separate invocations can therefore remember different state, even though their source code is identical.
What to remember
- Resolve names using source-code nesting, not the caller's local variables.
- Shadowing introduces a distinct binding with the same name.
- A returned function can retain access to an enclosing binding.
- A binding's current value may change without changing which binding a reference denotes.
- Separate enclosing calls can create independent captured state.
Example: A Fee Calculator That Remembers Its Rate
A booking service creates fee calculators using the Python code below. All amounts and fees are in dollars, and rates are dimensionless. A captured binding is an enclosing variable that a nested function retains access to. Here, fee and set_rate share access to the rate created by the same call to make_fee_calculator.
The Python nonlocal declaration lets set_rate update that enclosing variable. Assume the parts run in order, retaining the changes made in earlier parts. Report fees to two decimal places; the calculations here require no rounding adjustment.
rate = 0.05
def make_fee_calculator():
rate = 0.08
def fee(amount):
return amount * rate
def set_rate(new_rate):
nonlocal rate
rate = new_rate
return fee, set_rate
fee, set_rate = make_fee_calculator()
def checkout():
rate = 0.20
return fee(250)a) What fee does checkout() return?
First, resolve rate in the body of fee. The function has a local parameter named amount, but no local declaration of rate. Its enclosing function supplies the captured rate of ________. The module's 0.05 and the caller's 0.20 are different bindings.
Next, substitute the amount and the captured rate:
The fee returned by checkout() is 20.00 dollars. The caller's local declaration does not change the lexical lookup inside fee.
b) The service now executes set_rate(0.10), followed by fee(250). What fee does this call return?
The nonlocal declaration makes the assignment in set_rate update the same enclosing variable read by fee. The updated rate is ________. No new enclosing invocation is created by this update.
Use the current value of the shared binding:
The new fee is 25.00 dollars. Retaining access to a binding does not freeze its original value.
c) Next, the service executes second_fee, second_set_rate = make_fee_calculator(). Find the results of fee(150) and second_fee(150).
The original calculator still uses the binding updated in part b, whose rate is ________. The new call to make_fee_calculator creates a fresh local rate, initialized to ________. Its returned functions share that new binding with each other, but not with the original calculator.
Calculate the original calculator's fee:
Calculate the second calculator's fee using its independent binding:
Therefore, fee(150) returns 15.00 dollars, and second_fee(150) returns 12.00 dollars. Identical function source code can operate on distinct captured variables created by separate enclosing calls.
The Python function factory below nests three function definitions inside a module. Suppose Python must resolve a name used in the body of apply, and the name has not been found in any scope searched so far.
limit = 50
def build(base):
def make(scale):
def apply(n):
return n * scale + base + limit + abs(n)
return apply
return makeArrange the scopes in the order lexical scope searches them, from the scope searched first to the scope searched last.
1.
The module scope, which holds limit
2.
The local scope of apply, which holds n
3.
The scope of build, which holds base
4.
The scope of make, which holds scale
5.
The built-in scope, which holds abs
A scoring script uses the following Python code to add a saved adjustment to a score. What integer does report() return? Give a unitless answer to zero decimal places.
offset = 50
def make_adjuster():
offset = 6
def adjust(score):
return score + offset
return adjust
adjust = make_adjuster()
def report():
offset = 90
return adjust(20)