These examples show various ways to dynamically import modules, functions, or classes using importlib. This can be especially useful in scenarios like plugin systems, user-defined functionality, or optimizing performance by delaying imports.
import importlib
module_name = "datetime"
class_name = "datetime"
module = importlib.import_module(module_name)
cls = getattr(module, class_name)
now = cls.now()
print(now) # Output: Current date and time
import importlib
module_name = "nonexistent_module"
try:
module = importlib.import_module(module_name)
except ModuleNotFoundError:
print(f"Module '{module_name}' not found. Falling back to 'math'.")
module = importlib.import_module("math")
print(module.sqrt(9)) # Output: 3.0
import importlib
modules = ["math", "random", "os"]
imported_modules = {}
for module_name in modules:
imported_modules[module_name] = importlib.import_module(module_name)
print(imported_modules["math"].sqrt(16)) # Output: 4.0
print(imported_modules["random"].randint(1, 10)) # Random number between 1 and 10