Sub topic 4
What happens when you import: execution and sys.modules
This chapter assumes you can write functions and classes, run scripts from a terminal, and know the basic forms of import. It explains what Python does when it runs an import statement, and why a second import of the same module does almost nothing.
The steps of an import
When Python runs import name, it follows this sequence:
- Look for
namein thesys.modulescache. If it is there, bind that module object and stop. - Otherwise, find the file that defines the module (covered in a later chapter).
- Create an empty module object and store it in
sys.modulesunder its name. - Execute the file's code from top to bottom, using the module object's namespace as the global scope.
- Bind the module object to a name in the importing code.
Step 4 matters most. A module is not just read, it is run. Every top-level def, class, and assignment executes at that moment, and so does any top-level print call.
The sys.modules cache
sys.modules is a dictionary that maps module names to module objects. Python checks it first on every import. The code below shows the cache at work.
import sys
print("json" in sys.modules)
import json
print("json" in sys.modules)
print(sys.modules["json"] is json)The module body runs only on the first import. Later imports find the cached object and reuse it. This is why every file that imports json sees the same module object and the same global state.
You can see the single execution with a small experiment. Create a file named noisy.py:
# noisy.py
print("noisy is being executed")
counter = 0Then run this in the same directory:
import noisy
import noisy
import sys
noisy.counter += 1
import noisy as again
print(again.counter)
print(sys.modules["noisy"] is noisy)The message prints once. The final output is 1 followed by True, because both names point at the one cached module.
Why the module is cached before it finishes
Step 3 puts the module in sys.modules before step 4 runs its code. This ordering lets Python handle a module that is imported again while it is still loading, which happens in circular imports. In that case the second import receives a half-initialized module, with only the names defined so far.
If the module's code raises an exception, Python removes the entry from sys.modules. The next import then tries again from the start.
import sys
try:
import broken # a file whose first line is: raise RuntimeError("fail")
except RuntimeError as exc:
print("failed:", exc)
print("broken" in sys.modules)This prints failed: fail and then False.
Common errors
- Expecting a rerun. Editing a module and importing it again in the same session does nothing, because the cached version is returned. Restart the interpreter, or use
importlib.reload(a later chapter). - Side effects at import time. Code such as network calls or file writes at the top level runs once per process, on whichever import comes first. Keep module bodies to definitions where you can.
- Mutating shared state. All importers share one module object, so a change to
noisy.counteris visible everywhere.
Exercise
A module config.py contains print("loading config") at the top level. Two other files, a.py and b.py, both run import config, and a third script imports a and then b. How many times does "loading config" print, and why?
Show answer
Once. The first import config (reached through a) finds nothing in sys.modules, so Python executes the file and caches the module. The import in b finds the cached entry and skips execution.