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

Copy

import importlib

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

2. Dynamically Import a Function from a Module

Copy

import importlib

sqrt_function = getattr(importlib.import_module("math"), "sqrt")
print(sqrt_function(25))  # Output: 5.0

3. Dynamic Import Using a User Input

Copy

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: 120

4. Check if Module Exists Before Importing

Copy


5. Dynamic Import and Use of Class

Copy


6. Dynamic Import with Fallback

Copy


7. Dynamic Import of Multiple Modules in a Loop

Copy


8. Dynamic Import and Method Call Using importlib

Copy


9. Dynamic Import of a Custom Module

Suppose you have a file my_module.py with a function greet:

Copy

You can dynamically import and use it:

Copy


10. Dynamic Import with Lazy Loading

Copy

Last updated