6. Dynamic Imports
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.
1. Basic Dynamic Import of a Module
import importlib
math_module = importlib.import_module("math")
print(math_module.sqrt(16)) # Output: 4.02. Dynamically Import a Function from a Module
import importlib
sqrt_function = getattr(importlib.import_module("math"), "sqrt")
print(sqrt_function(25)) # Output: 5.03. Dynamic Import Using a User Input
import importlib
module_name = input("Enter module name: ") # e.g., "math"
function_name = input("Enter function name: ") # e.g., "factorial"
module = importlib.import_module(module_name)
function = getattr(module, function_name)
print(function(5)) # For input "math" and "factorial", Output: 1204. Check if Module Exists Before Importing
5. Dynamic Import and Use of Class
6. Dynamic Import with Fallback
7. Dynamic Import of Multiple Modules in a Loop
8. Dynamic Import and Method Call Using importlib
9. Dynamic Import of a Custom Module
Suppose you have a file my_module.py with a function greet:
You can dynamically import and use it:
10. Dynamic Import with Lazy Loading
Last updated