Python Reference ยท Standard Library: Concurrency, Network and Tools
The importlib module
Reference for Python's importlib: import_module for dynamic imports, reload, importlib.util.find_spec, loading modules from files, sys.modules and metadata.
importlib exposes the machinery behind the import statement as ordinary functions. Its most common use is importlib.import_module("name"): importing a module whose name you only know at run time, for example when loading a plugin chosen in a configuration file.
The same package lets you check whether a module is installed without importing it, reload a module you have edited, load a module from an arbitrary file path, and read the metadata (version, entry points) of installed packages.
import importlib module = importlib.import_module("json") print(module.dumps({"ok": True}))
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Loading a module from a file path and reading package metadata (read-only, because the runner has no files or installed distributions to point at):
import importlib.util import importlib.metadata spec = importlib.util.spec_from_file_location("plugin", "/path/to/plugin.py") plugin = importlib.util.module_from_spec(spec) spec.loader.exec_module(plugin) print(importlib.metadata.version("requests")) # e.g. 2.32.3 print(importlib.metadata.entry_points(group="console_scripts"))
Syntax
importlib.import_module(name, package=None) importlib.reload(module) importlib.invalidate_caches() importlib.util.find_spec(name, package=None) importlib.util.spec_from_file_location(name, location) importlib.util.module_from_spec(spec)
| Name | Description |
|---|---|
name |
Module name as a string, dotted for submodules. A leading dot means a relative import. |
package |
The anchor package for a relative name such as ".sibling". Required in that case. |
module |
An already imported module object to re-execute. |
location |
Path of a .py file for spec_from_file_location. |
Return value: import_module() returns the module named by the full dotted name (unlike __import__("a.b"), which returns the top package). reload() returns the same module object, updated in place. find_spec() returns a ModuleSpec or None.
Raises: ModuleNotFoundError (a subclass of ImportError) when a module cannot be found, TypeError for a relative name without package, and ImportError if reloading a module that was never imported.
Usage notes
- Prefer plain
importwhen the name is known while you write the code. Dynamic imports hide dependencies from readers, linters and bundlers. - Module cache: each module executes once; later imports return the object in
sys.modules. Deleting the entry forces a fresh import. reload()is shallow. Names bound before the reload (from mod import f) still point to the old objects, and instances keep their old class. It is a development convenience, not a production update mechanism.find_spec()imports parents. Checkinga.bimports packageafirst. It does not importa.bitself.- Never import names from untrusted input. Importing runs code, so a user-controlled module name is a code-execution hole. Restrict choices to an allow-list.
- Files created while running may not be seen until
importlib.invalidate_caches()is called. - Metadata:
importlib.metadata.version("pkg")reads an installed distribution's version; it needs the package to be installed, not importable. - Resources:
importlib.resources.files("pkg")locates data files that ship inside a package, working even in zip files. - Import hooks: custom finders and loaders (
sys.meta_path) let you import from databases, archives or generated code, but that is advanced.
Related
sys,inspect,ImportErrorgetattr(),pathlib- Lessons: Modules, Packages and pip