173. Dynamic Importing of Modules
import importlib
module_name = "math"
math_module = importlib.import_module(module_name)
print(math_module.sqrt(16)) # Output: 4.0import importlib
module_name = "math"
function_name = "pow"
math_module = importlib.import_module(module_name)
power_function = getattr(math_module, function_name)
print(power_function(2, 3)) # Output: 8.0import importlib.util
module_path = "/path/to/custom_module.py"
module_name = "custom_module"
spec = importlib.util.spec_from_file_location(module_name, module_path)
custom_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(custom_module)
# Assuming the module has a function `greet`
print(custom_module.greet())Last updated