This may seem odd, but you can change the __path__ module variable and then import from it. Then you do not bother with the global import space in sys.path.
Edit: if directories are loaded at run time, you do not need the plugins.py file to store them. A dynamic dynamic module can be created:
main.py:
#create the plugins module (pseudo-package) import sys, os sys.modules['plugins'] = plugins = type(sys)('plugins') plugins.__path__ = [] for plugin_dir in ['plugins1', 'plugins2']: path = os.path.join(sys.path[0], 'addons', plugin_dir) plugins.__path__.append(path)
After creating the dynamic module, you can load the plugins as before using import_module or __import__ :
from importlib import import_module myplugins = [] for plugin in ['myplugin1', 'myplugin2']: myplugins.append(import_module('plugins.' + plugin)) myplugins[-1].init()
addons / plugins1 / myplugin1.py:
def init(): print('myplugin1')
addons / plugins2 / myplugin2.py:
def init(): print('myplugin2')
I have never used this, but it works in both Python 2 and 3.
source share