How can I import a module dynamically given its name as string?
Let's import a module dynamically using its string name via the import_module
function in the importlib
library:
Replace 'json'
with the name of the module you wish to use and voila, you're good to go.
Harnessing dynamic imports
The charm of dynamic imports arises when you want your Python code to be more than just a script. Imagine extensions, plugins, and on-demand command modules. Yes, all that jazz!
Python 2 or 3, we've got you covered
Thanks to importlib
, dynamic importing can swing both ways — Python 2 and Python 3:
Relative imports, absolute resolution
Relative imports can trick you; when you're dealing with them, prepare to lock, load, and import_module
:
Import a module crowd
For a crowd of modules, spin your import_module
to load them up:
Importing from a script file
Got a file path rather than a module name? No worries, Python's got an import trick for that too:
sys.modules: The genie's lamp of modules
Every imported module is stored in the sys.modules
magic lamp. Just rub the lamp and call your wish:
Want to peek inside a module?
If you ever need to inspect your new arrival, Python comes equipped with its module peeking window:
Dynamic function calls from dynamic imports
One function call to rule them all, brought dynamically into this world:
Extending functionality: A plugin story
Suppose new commands are party crashers and you want to include them without touching the main application. How about this?
Tips for smooth cruising
- Keep the legacy
__import__
in the attic unless you're dwelling in the past. - Always stay on guard for ImportErrors and ensure your app doesn't trip and fall.
- Ensure to use absolute module names for a no-confusion spell.
The grand reveal
This might feel like a neat programming trick, but it's truly a realization of fundamental design patterns. Think plugins, components, or commands in a CLI tool. Embracing dynamic imports turns your code into a modular, flexible, and heavily extendable masterpiece.
Was this article helpful?