How does importlib let you dynamically import a module by name at runtime?
Short answer
importlib.import_module(name) programmatically imports a module given its string name, which is essential when the module to load isn't known until runtime -- such as a plugin system loading modules based on configuration or discovered files.
Advertisement
AModel answer
importlib.import_module(name) programmatically imports a module given its string name, which is essential when the module to load isn't known until runtime -- such as a plugin system loading modules based on configuration or discovered files. It returns the module object just as a static `import` statement would bind it.
import importlib
module_name = 'json' # could come from config or user input
mod = importlib.import_module(module_name)
print(mod.dumps({'key': 'value'}))Real-world example
A plugin architecture reads a list of enabled plugin module names from a config file and uses importlib.import_module() to load each one dynamically without hardcoding import statements.
Likely follow-ups
- How does importlib.reload() differ from a fresh import_module call?
- How do you dynamically import from a file path, not just a module name?
Related topics