Local and Module-Level Name Lookup
Python resolves names using the function's lexical context. An assignment can alter which binding an earlier read in the same function uses.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Read from the selected scope
A function may read a module-level unit_price if its body does not create that name locally. A plain assignment to unit_price anywhere in the function body makes it local throughout that body, subject to declarations and nested scopes. Reading it before assignment can raise UnboundLocalError. Check the binding rules before assuming the global value will be used.
Let the call state what it needs
A subtotal routine can receive unit_price and quantity as parameters. Calling it with 4 and 3 always computes 12 if the only operation is multiplication. A module setting can still provide the first argument. This separates a stable calculation from its script entry point and lets tests pass meaningful prices.[1][2]
Distinguish a read from a rebind
A Python function can read a module's limit without qualifying the name when it has no conflicting local binding. Adding an assignment to limit changes the local-name analysis for that function. If a previous line in the same call then reads it before assigning it, Python can raise UnboundLocalError. Changing the module's value does not supply the missing local binding. This can be surprising when the assignment appears only in a later branch. See names and binding for the role of the right-hand read.
A function can also mutate an object reached through a name without assigning that name. A call such as labels.append("new") changes the list while preserving the name binding. labels = labels + ["new"] binds the local name as part of assignment under the normal rules. Trace both operations to see which object is changed.
Give each call the value it is allowed to use
For a subtotal function, pass a unit price as an argument. A caller can still obtain that price from a module setting or configuration file. Testing two prices then just requires two ordinary calls. This avoids depending on the order in which tests modify a shared module. Explicit dependency arguments extend the idea to clocks, readers, and other inputs.
Use a deliberate example with separate prices of 3 and 5 and quantity 2. The two calls should yield 6 and 10. If both yield the value from one module setting, find where the computation still reads outside its intended input. Keeping the lookup boundary visible makes that test informative.