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 have seen the basic forms of import (import x, from x import y, import x as z). Here you will learn what Python does when it runs an import statement. You will also learn why a module's top-level code runs only once.
The import statement is executable code
An import statement runs at the moment Python reaches it. It is not a declaration that the compiler resolves ahead of time. When Python executes import json, it does these steps:
- It looks for the name
jsonin the cachesys.modules. - If the name is there, Python reuses that module object and does no more work.
- If it is missing, Python finds the module (see the later chapter on
sys.path), creates an empty module object, and stores it insys.modules. - Python runs the module's code from top to bottom, inside that module object's namespace.
- Python binds a name in the importing scope to the module object.
Step 3 stores the module before step 4 runs it. This ordering matters for circular imports, which a later chapter covers.
Execution happens once
Top-level statements in a module run when the module is first imported. Later imports of the same module reuse the cached object, so those statements do not run again. Create two files to see this.
# counter_demo.py
print("counter_demo is being executed")
count = 0
def increment():
global count
count += 1
return count# main.py
import counter_demo
import counter_demo
from counter_demo import increment
print(increment())
print(increment())Running python main.py prints this:
counter_demo is being executed
1
2The message appears once, even though three import statements name the module. The state in count also persists. Both increment() calls change the same module-level variable, because every importer holds a reference to the same module object.
The second import counter_demo and the from counter_demo import increment both find the module in sys.modules. The from form still imports the whole module first. It then copies one name out of the module's namespace into yours. Importing a single function does not avoid running the rest of the file.
Inspecting sys.modules
sys.modules is an ordinary dictionary. The keys are fully qualified module names, such as "os.path". The values are module objects. You can read it, and you can also modify it.
import sys
print("json" in sys.modules)
import json
print("json" in sys.modules)
print(sys.modules["json"] is json)
print(json.__name__)The first line usually prints False in a plain script, though some tools and interpreters preload modules, so do not depend on it. The next two lines print True. The module's __name__ attribute holds the same string that is used as its key in sys.modules.
Many standard modules are already in sys.modules before your first line runs, because Python itself needs them at startup. Examples are sys, builtins, and os.
Submodules appear as separate entries
Importing os.path puts more than one entry in the cache. Importing a dotted name imports each parent package first.
import sys
import xml.dom.minidom
for name in ("xml", "xml.dom", "xml.dom.minidom"):
print(name, name in sys.modules)All three lines print True. Each level is its own module object with its own execution.
What the import binds
The import statement binds names in the current scope, and the form decides which names. This is why sys.modules and your own namespace are different things. The cache holds modules by name. Your code holds only the names you bound.
| Statement | Cached in `sys.modules` | Name bound in your scope |
|---|---|---|
| `import json` | `json` | `json` |
| `import json.decoder` | `json`, `json.decoder` | `json` (the top package) |
| `import json as j` | `json` | `j` |
| `from json import loads` | `json` | `loads` |
Deleting your own name does not unload the module. After del json, the module is still in sys.modules, and import json binds it again instantly without re-executing anything.
Seeing the cache in action
Modules are shared objects, so a change made through one reference is visible through all of them.
import sys
import string
alias = sys.modules["string"]
print(alias is string)
string.my_flag = "set from here"
import string as again
print(again.my_flag)Both lines print True and set from here. Adding attributes to a standard library module is a bad idea in real code. It shows, though, that there is one module object and many references to it.
Forcing a fresh import
Because the cache decides what runs, removing an entry makes the next import execute the file again.
import sys
import counter_demo
first = counter_demo
del sys.modules["counter_demo"]
import counter_demo as second
print(first is second)
print(first.count, second.count)The file prints its message twice, once for each execution. Then first is second is False, because the second import built a new module object. Any code that kept a reference to the old object still sees the old state.
Import-time side effects
Since the module body runs at import time, anything at the top level of a file is a side effect of importing it. This includes printing, opening files, reading environment variables, and connecting to a database. Common consequences are:
- Importing a module can be slow if its top level does heavy work.
- An import can fail for reasons unrelated to what you wanted, such as a missing config file.
- The order of imports can change behavior if modules modify shared state.
A good habit is to keep top-level code limited to definitions: functions, classes, and constants. Put work inside functions that callers invoke on purpose.
Failed imports
If a module raises an exception while executing, the import fails and Python removes the half-built module from sys.modules. The next attempt to import it runs the file again from the start.
# broken.py
print("loading broken")
raise RuntimeError("boom")import sys
for attempt in (1, 2):
try:
import broken
except RuntimeError as exc:
print("attempt", attempt, "failed:", exc)
print("broken" in sys.modules)The output shows loading broken twice, and the last line prints False. A failed import does not leave a partly initialized module for later importers to find. Keep in mind that side effects the module already performed before the error, such as printed text or created files, are not undone.
A missing module is a different failure. It raises ModuleNotFoundError, a subclass of ImportError, and nothing is cached.
Common errors
- Expecting top-level code to run on every import. It runs once per process, unless the cache entry is removed.
- Editing a module and re-importing it in a long-running session such as the interactive prompt or a notebook. The cached object is reused, so your edit has no effect until you restart or reload.
- Assuming
from x import yis cheaper thanimport x. Both execute all ofxon first use. - Assuming
del nameunloads a module. It only removes your binding. - Keeping references to old module objects after clearing the cache, then comparing classes across the two copies.
Exercise
A file config.py contains print("loading config") and settings = {}. Two other modules, a.py and b.py, both run import config, and main.py imports a and then b. How many times is "loading config" printed, and if a.py runs config.settings["debug"] = True, what does b.py see in config.settings?
Show answer
It is printed once. The first import (from a) executes config.py and caches it in sys.modules. The import in b finds the cached module and does not run it again. Both modules hold the same module object, so b sees {"debug": True}.
Exercise
You run import counter_demo, then del counter_demo, then import counter_demo again. Is the file executed a second time? Explain what the second import does, and name one way to make it execute again.
Show answer
No. del counter_demo removes only your name binding, and the module object stays in sys.modules. The second import finds it there and just rebinds the name. To run the file again, remove the entry with del sys.modules["counter_demo"] before importing, or use importlib.reload.