Dynamic Imports with importlib Module
1Concept
`importlib.import_module()` dynamically imports modules programmatically from string names at runtime, enabling plugin architectures, runtime dependency resolution, and configuration-driven service loading.
2Architecture Diagram
Config: "services.payment.StripeService" ---> importlib.import_module() ---> Loaded Class
3Code Example
Python 3.12
import importlib
# Dynamically import standard library module
module_name = "json"
imported_lib = importlib.import_module(module_name)
payload = imported_lib.dumps({"service": "DynamicLoader", "version": 3.12})
print(f"Dynamically Loaded Module: {imported_lib.__name__}")
print(f"Result: {payload}")4Expected Output
Dynamically Loaded Module: json
Result: {"service": "DynamicLoader", "version": 3.12}5Key Takeaways
- ✓`importlib.import_module()` supports relative imports using the `package` argument.
- ✓Use `importlib.reload(module)` to reload updated code during interactive development.
- ✓Validate string inputs against a whitelist to prevent arbitrary code execution vulnerabilities.