Module Namespaces and Shared Bindings
Core idea
Each module has its own global namespace. A function defined in a module resolves its global names there, not in the caller’s module. Attribute access such as settings.rate reads the binding in the module object.
Separate same-named variables
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_rates.py
rate = 3def total(count): return count * rateSave the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
import bm_ratesrate = 100print(bm_rates.total(4), rate)Output: 12 100. total uses its own module’s rate (3); the caller’s rate is 100.
Observe a later rebinding
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_settings.py
rate = 3Save the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
import bm_settingsfrom bm_settings import ratebm_settings.rate = 8print(rate, bm_settings.rate)Output: 3 8. The direct import kept a reference to the old integer. Rebinding the module attribute does not rebind the local name.
Inspect a known module name
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_labels.py
label = "A"Save the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
import bm_labelsprint(bm_labels.__name__)print(bm_labels.__dict__["label"])Output: bm_labels then A. name identifies the imported module and dict exposes its namespace. Inspect only known nonsensitive bindings.
Common mistake
An imported name is not a live link to every future assignment in its original module. Mutable objects may still be shared, so rebinding and mutating must be distinguished.
Practice
In a module with a list of labels, import the list directly and also import the module. Predict what happens when the original list is appended to, then when the module attribute is rebound to a new list.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Trace module-owned names
Check your understanding of module namespace.
A rates module defines rate = 4 and a function that returns rate. A caller has rate = 9. What does the imported function return?
After `from settings import rate`, settings.rate is rebound from 3 to 8. What is the directly imported rate (assuming an integer)?
Which expression reads a known binding called label in an imported module m?
If two modules share the same imported list, what happens when one appends an item?