Sub topic 17
Dynamic imports and reloading
This chapter assumes you know how import runs a module once and caches it in sys.modules, and how sys.path decides where Python looks. Here you will import modules whose names are only known at run time, load a file from an arbitrary path, and re-run a module you have already imported.
Importing by name
An import statement needs the module name written in the source. When the name comes from a config file, a command-line option, or a plugin list, use importlib.import_module. It takes a string and returns the module object. It uses the same search and the same sys.modules cache as import.
import importlib
import sys
mod = importlib.import_module("json.decoder")
print(mod.__name__)
print("json.decoder" in sys.modules)For a dotted name, the parent packages are imported first. For a relative name such as ".util", pass the anchor package as the second argument: import_module(".util", package="shapes").
Loading a file from a path
Sometimes the file is not on sys.path, for example a user-supplied plugin. Build a module from a file location with importlib.util.
import importlib.util
import sys
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as folder:
plugin_file = Path(folder) / "hello_plugin.py"
plugin_file.write_text("def run():\n return 'plugin ran'\n")
spec = importlib.util.spec_from_file_location("hello_plugin", plugin_file)
module = importlib.util.module_from_spec(spec)
sys.modules["hello_plugin"] = module
spec.loader.exec_module(module)
print(module.run())The three steps are: create a spec, create an empty module from it, then execute the file's code inside that module. Registering the module in sys.modules before executing it mirrors what a normal import does, so code inside the plugin that imports itself still works.
Reloading a module
A second import of the same name returns the cached module and does not re-read the file. importlib.reload(module) runs the file's code again inside the existing module object.
import importlib
import sys
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as folder:
sys.path.insert(0, folder)
path = Path(folder) / "settings_demo.py"
path.write_text("LEVEL = 1\n")
importlib.invalidate_caches()
import settings_demo
print(settings_demo.LEVEL) # 1
path.write_text("LEVEL = 20\n")
print(settings_demo.LEVEL) # still 1: cached
importlib.reload(settings_demo)
print(settings_demo.LEVEL) # 20
sys.path.remove(folder)importlib.invalidate_caches() makes the finders notice files created after Python started. The second file has a different length on purpose. Python's bytecode cache checks the modification time (in whole seconds) and the file size, so two edits in the same second with the same size can load stale bytecode.
What reloading does not do
| Situation | Result after `reload(mod)` |
|---|---|
| Code used `from mod import f` | The name `f` still points to the old function. |
| Objects created from an old class | They keep the old class. |
| Submodules of a package | They are not reloaded. |
| Names deleted from the file | They stay in the module, because the namespace is reused. |
Exercise
You call importlib.reload(config) after editing config.py, but another module that ran from config import TIMEOUT still sees the old value. Why, and how can that module see the new value?
Show answer
from config import TIMEOUT bound the name TIMEOUT in the other module to the old object, and reload does not update names bound elsewhere. The other module should use import config and read config.TIMEOUT at use time. Alternatively, it can re-run its own from config import TIMEOUT after the reload.