173. Dynamic Importing of Modules

Snippet 1: Basic Dynamic Import

import importlib

module_name = "math"
math_module = importlib.import_module(module_name)
print(math_module.sqrt(16))  # Output: 4.0

Snippet 2: Importing a Specific Function

import 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.0

Snippet 3: Importing a Module from a Custom Path

import 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())

Snippet 4: Dynamic Import Based on User Input


Snippet 5: Listing Attributes of a Dynamically Imported Module


Snippet 6: Reimporting a Module


Snippet 7: Dynamically Importing Submodules


Snippet 8: Importing Classes Dynamically


Snippet 9: Dynamic Import with Exception Handling


Snippet 10: Dynamically Importing a Function and Calling It


Last updated