Explain Codes LogoExplain Codes Logo

How can I import a module dynamically given its name as string?

python
dynamic-imports
importlib
module-resolution
Anton ShumikhinbyAnton Shumikhin·Nov 24, 2024
TLDR

Let's import a module dynamically using its string name via the import_module function in the importlib library:

from importlib import import_module module = import_module('json') data = module.loads('{"key": "value"}') # Conjure up some JSON magic

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:

try: # Python 3.1+ with fallback for Python 2 from importlib import import_module except ImportError: # if it's not staying in the future, it's living in the past from importlib import import_module

Relative imports, absolute resolution

Relative imports can trick you; when you're dealing with them, prepare to lock, load, and import_module:

module_relative = import_module('.module', package='my_package')

Import a module crowd

For a crowd of modules, spin your import_module to load them up:

modules_to_import = ['module1', 'module2', 'module3'] loaded_modules = [import_module(name) for name in modules_to_import] # Boom, boom, and boom!

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:

from importlib.util import spec_from_file_location, module_from_spec spec = spec_from_file_location("my_module", "/path/to/file.py") # Locate the module module = module_from_spec(spec) # Create the module object spec.loader.exec_module(module) # Kaboom! The module is loaded

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:

import sys my_cached_module = sys.modules['my_module'] # "Aladdin, your module is ready!"

Want to peek inside a module?

If you ever need to inspect your new arrival, Python comes equipped with its module peeking window:

print(dir(module)) # "Who's that sneaking in my module?"

Dynamic function calls from dynamic imports

One function call to rule them all, brought dynamically into this world:

function_to_call = 'my_function' getattr(module, function_to_call)(args) # "Hey 'my_function', say hello to the 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?

def execute_command(command_name): command = import_module(f"commands.{command_name}") return command.run() # "Hello command, ready to rock 'n roll?"

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.