QA
Intermediate LevelPython

How do you dynamically load and reload Python modules at runtime using importlib.import_module() and reload()?

❓ Interview Prompt: Explain `importlib.import_module()`, dynamic module resolution, `importlib.reload()`, and building plugin architectures.

The 'importlib' module allows programmatically importing modules at runtime:

Primary Use Cases:

•
'importlib.import_module('plugins.my_plugin')': Dynamically loads modules by string path (essential for building plugin architectures!).
•
'importlib.reload(module)': Reloads a previously imported module from disk without restarting the Python process.

Code Implementation Example

python
import importlib

def load_plugin(plugin_name):
    # Dynamically import module by string name!
    module = importlib.import_module(f'math')
    func = getattr(module, 'sqrt')
    return func(16)

print(load_plugin('math')) # 4.0
💡Loading modules dynamically at runtime using importlib.import_module().
🎯 Interview Key Takeaway

Use importlib.import_module() to build dynamic plugin architectures loaded by string name.

#importlib#Dynamic Import#Plugins#Intermediate
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?