How can I perform a Python dynamic import given the module name as a string?
I’m developing a Python application that takes a command as an argument, for example:
$ python myapp.py command1
The goal is to make the application extensible, so I can add new modules for commands without modifying the main application’s source code. The directory structure looks like this:
myapp/
__init__.py
commands/
__init__.py
command1.py
command2.py
foo.py
bar.py
I want the application to dynamically find available command modules and execute the corresponding one at runtime.
Python provides the __import__()
function, which allows importing modules by name as a string:
__import__(name, globals=None, locals=None, fromlist=(), level=0)
This function imports the specified module, and you can customize the globals, locals, and other parameters.
Currently, I’m using something like this:
command = sys.argv[1]
try:
command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"])
except ImportError:
# Display error message
command_module.run()
This works well, but I’m curious if there’s a more idiomatic or preferred way to handle this in Python, specifically with dynamic imports.
(Note: I am not looking to use eggs or plugins in this application, as it’s not open-source and doesn’t require external extensions.)