Say we want to import a script dynamically, i.e. the name is constructed at runtime. I use this to detect plugin scripts for some program, so the script may not be there and the import may fail.
from importlib import import_module
# ...
subpackage_name = 'some' + dynamic() + 'string'
try:
subpackage = import_module(subpackage_name)
except ImportError:
print('No script found')
How can we make sure to only catch the possible import failure of the plugin script itself, and not of the imports that may be contained inside the plugin script?
Side note: this question is related, but is about static imports (using the import
keyword), and the provided solutions don't work here.
ImportError
s in Python havemessages you can readname
attributes you can use if you have the exception object:Since Python 3.3,
ImportError
objects have hadname
andpath
attributes, so you can catch the error and inspect the name it failed to import.