Imports and Bound Names

An import can bind a module object or a name drawn from it. That choice affects what another module observes after a subsequent assignment.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Read the import as a binding
  2. Try a two-module counterexample
  3. Follow the two ways of reading a setting
  4. Establish a dependable configuration boundary

Read the import as a binding

import settings places the module under the name settings. A later read of settings.limit looks up the current attribute. from settings import limit binds the exported object to the local name limit at import time. A later reassignment of the module attribute leaves that local name binding as it was. Mutating a shared object is a separate operation.

Try a two-module counterexample

Assume the module starts with a limit of four. A consumer imports both forms and the module later assigns its limit to seven. The qualified read gives seven, and the imported number remains four. Make program configuration explicit at the entry point if consumers ought to share a stable snapshot.[1][2]

Follow the two ways of reading a setting

Imagine that a module has a numeric attribute limit. Setting that attribute to five creates a binding on the module. A qualified use such as settings.limit reads the module attribute at the moment the expression is evaluated. An import of that specific value into another module binds that importing module's local name to the object found during import. Reassigning the original attribute to eight does not automatically rebind that earlier name.

When the exported object is a list, a different observation is possible. Two modules may both hold references to the same list. Mutating the list through either reference changes the contents they both read. Replacing the entire exported list is a new binding in the exporting module. Name bindings and mutable objects explain why the two scenarios differ.

Establish a dependable configuration boundary

A background job can read all of its relevant settings at the start and pass them to the function doing the work. That lets each job use one coherent snapshot even if later jobs receive different settings. For a test, supply two distinct limits to consecutive runs and check their results. Refer to passed configuration for choices about where a value should be observed.

Review top-level work too. An import may run initialization on the first successful load under its module name. Keep unrelated command actions behind a script entry point so a test can import functions without starting a job.

References

  1. Python Software Foundation, Python Language Reference: Execution Model ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩