Flexible imports in python
Sometimes (In my case for a plugin-like structure) you start with the following:
.
├── logic.py
├── plugins
├── __init__.py
├── plug_a.py
├── plug_b.py
__init__.py
__all__ = ['plug_a', 'plug_b']
Ready, right?
in logic.py
:
from plugins import *
for modname, mod in sys.modules.iteritems():
if modname.startswith(plugins.__name__):
# run plugin or whatever
That's good and all, but if there were problems in any of these plugins, it would fail when we do a from plugins import *
. So instead:
for plugin in plugins.__all__:
try:
__import__('{}.{}'.format(plugins.__name__, plugin))
except:
print plugin, 'could not be loaded'
The except is a little broad and could be narrowed to ImportError maybe, but who knows what else could hide in there.