Sub topic 17
Dynamic imports and reloading
This chapter covers loading modules from names or paths that are only known at run time, and re-running a module that is already loaded. It assumes you know the import statement, the sys.modules cache, sys.path, and the idea that a module is an object with its own namespace. Those come from earlier chapters.
Importing by string with import_module
The import statement needs a name written in the source code. When the name comes from a config file, a command-line option, or a plugin list, you have a string instead. importlib.import_module takes that string and runs the same import process as the statement.
import importlib
import sys
mod = importlib.import_module("json.decoder")
print(mod.__name__)
print("json.decoder" in sys.modules)The function returns the module you named. The built-in __import__("json.decoder") returns the top-level json package instead, which is one reason to prefer import_module in your own code.
A common use is turning a string such as "json:dumps" into an object:
import importlib
def load_attr(path):
module_name, _, attr = path.partition(":")
module = importlib.import_module(module_name)
return getattr(module, attr)
dumps = load_attr("json:dumps")
print(dumps({"a": 1}))For a relative name, pass the anchor package as the second argument. A leading dot has no meaning without it.
import importlib
mod = importlib.import_module(".decoder", package="json")
print(mod.__name__)Handling a missing module correctly
A dynamic import can fail for two different reasons, and they raise the same exception type:
- The module you asked for does not exist.
- The module exists, but it imports something else that does not exist.
ModuleNotFoundError has a name attribute that holds the module that could not be found. Compare it to the name you requested so you do not hide the second kind of failure.
import importlib
def try_import(name):
try:
return importlib.import_module(name)
except ModuleNotFoundError as exc:
if exc.name == name or name.startswith(exc.name + "."):
return None
raise
print(try_import("no_such_module"))
print(try_import("json") is not None)If you only want to know whether a module can be found, importlib.util.find_spec(name) returns a spec or None, and it does not execute the module. For a dotted name, it imports the parent packages first.
Loading a module from a file path
Sometimes the file is not on sys.path, for example a user-supplied script. Build a spec from the path, create the module object, and execute it.
import importlib.util
import sys
from pathlib import Path
def load_from_path(name, path):
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise ImportError(f"cannot load {path}")
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
try:
spec.loader.exec_module(module)
except BaseException:
del sys.modules[name]
raise
return module
path = Path("hello_plugin.py")
path.write_text("GREETING = 'hi'\n")
mod = load_from_path("hello_plugin", path)
print(mod.GREETING)Three details matter here:
- The module is put in
sys.modulesbefore it runs. Code inside the module that imports itself, and tools such aspickleanddataclasses, look it up there. - If execution fails, the half-built module is removed. This mirrors what the normal import statement does.
- The name you choose is not checked against anything. If it matches an existing module, you will replace that entry in
sys.modules.
What the import functions share
The three entry points do different amounts of the work. The table shows which step each one performs.
| Tool | Finds the module | Executes it | Stores it in `sys.modules` |
|---|---|---|---|
| `importlib.import_module(name)` | Yes, via `sys.path` | Yes, if not cached | Yes |
| `importlib.util.find_spec(name)` | Yes | No | No |
| `spec_from_file_location` with `module_from_spec` and `exec_module` | No, you supply the path | Yes, every time you call it | Only if you do it yourself |
Because import_module consults the cache first, calling it twice with the same name gives you the same object and runs the file once. The manual path-loading route has no cache check. Calling it twice creates two separate module objects.
Reloading a module
importlib.reload(module) runs the module's source again. It reuses the existing module object and its __dict__. The new code executes inside that same namespace, so names the file defines are overwritten with new values.
import importlib
import sys
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
sys.path.insert(0, tmp)
mod_file = Path(tmp) / "settings_demo.py"
mod_file.write_text("LEVEL = 'info'\n")
import settings_demo
from settings_demo import LEVEL
print(settings_demo.LEVEL, LEVEL)
mod_file.write_text("LEVEL = 'debug-verbose'\n")
importlib.reload(settings_demo)
print(settings_demo.LEVEL, LEVEL)
sys.path.remove(tmp)
del sys.modules["settings_demo"]The output is:
info info
debug-verbose infoThe module attribute changed. The separate name LEVEL, bound earlier with from ... import, still points to the old string. That one result explains most reload surprises.
Gotchas when reloading
- From-imports go stale. Any
from mod import nameelsewhere keeps the old object. Access the value asmod.name, or run the from-import again. - Existing instances keep the old class. Reload creates a new class object. Instances made earlier still belong to the old class, so
isinstance(old, mod.Thing)becomesFalse. - Deleted names survive. If you remove a function from the source, the old function stays in the namespace after reload, because nothing deletes it.
- Dependencies are not reloaded. Reloading
adoes not reload the modulesaimports. You must reload them yourself, in dependency order. - Reload needs a live module. It raises
ImportErrorif the module is no longer insys.modules, andTypeErrorif you pass a string. - Stale caches. If you create a new file while the program runs, call
importlib.invalidate_caches()before importing it so the path finders notice it. - Compiled extensions. Extension modules written in C generally cannot be reloaded in a useful way.
Choosing an approach
Use a normal import statement whenever the name is fixed, because tools and readers can follow it. Use import_module when the name is data. Use spec_from_file_location only for files outside sys.path. Use reload only when you can accept the staleness rules above.
Exercise
A program runs from config import DEBUG, and later calls importlib.reload(config) after the file config.py changed DEBUG from False to True. What does DEBUG evaluate to in the program afterwards, what does config.DEBUG evaluate to, and why?
Show answer
DEBUG is still False and config.DEBUG is True. Reload re-executes config.py in the existing module object, so the module attribute gets the new value. The name DEBUG in your program was bound once to the old object by the from-import, and reload does not rebind it. To see the new value, read config.DEBUG or run from config import DEBUG again.
Exercise
You write try: importlib.import_module("plugins.csv_export") except ModuleNotFoundError: print("plugin not installed"). The module plugins/csv_export.py exists but contains import pandas, and pandas is not installed. What does the user see, and how do you change the handler so the real problem is reported?
Show answer
The user sees "plugin not installed", which is misleading, because the plugin was found and its dependency is what is missing. Catch the exception as exc and check exc.name. Treat it as "plugin not installed" only if exc.name is "plugins.csv_export" (or a parent such as "plugins"). Otherwise re-raise, so the traceback shows that pandas is missing.