Understand Module Initialization and Import Caching
Core idea
After an ordinary successful import, Python normally keeps the module object in sys.modules, a process-local module cache. A second import by the same fully qualified name generally reuses that object instead of executing the module body again.
Observe one initialization
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_counter.py
print("Loading")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_counterimport bm_counter as againprint(bm_counter is again)Output: Loading once, then True. Both names point to the same module object.
Observe shared module state
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_state.py
count = 0Save the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
import bm_stateimport bm_state as againbm_state.count += 2print(again.count)Output: 2. Both import names observe the same module state.
Explicitly reload a trusted toy module
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_state.py
count = 0Save the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
import importlibimport bm_statebm_state.count = 8importlib.reload(bm_state)print(bm_state.count)Output: 0. reload reruns the module code in its existing namespace. It is not a full reset of all external references; names no longer defined by the source may remain.
Common mistake
Do not rely on repeated imports to reset state. A new process has a separate cache, and reloading is not a general application reset mechanism. Avoid manipulating the real import cache in ordinary application code.
Practice
Run the first example twice as separate processes. Within each run, predict how many times Loading appears; then compare with two imports in one process.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Predict cache behavior
Check your understanding of import caching.
A module prints Loading at top level. It is imported twice by the same name successfully in one fresh process. How many times does Loading normally appear?
What does an alias in a second ordinary import normally refer to?
What does importlib.reload(m) normally do to a trusted Python module?
How do two separate interpreter processes normally relate to module caches?