Python › Modules & Packaging
How does importlib let you dynamically import a module by name at runtime?
AdvancedAnswer
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.