I'd like to load a module dynamically, given its string name (from an environment variable). I'm using Python 2.7. I know I can do something like:
import os, importlib
my_module = importlib.import_module(os.environ.get('SETTINGS_MODULE'))
This is roughly equivalent to
import my_settings
(where SETTINGS_MODULE = 'my_settings'
). The problem is, I need something equivalent to
from my_settings import *
since I'd like to be able to access all methods and variables in the module. I've tried
import os, importlib
my_module = importlib.import_module(os.environ.get('SETTINGS_MODULE'))
from my_module import *
but I get a bunch of errors doing that. Is there a way to import all methods and attributes of a module dynamically in Python 2.7?
If you have your module object, you can mimic the logic
import *
uses as follows:However, this is almost certainly a really bad idea. You will unceremoniously stomp on any existing variables with the same names. This is bad enough when you do
from blah import *
normally, but when you do it dynamically there is even more uncertainty about what names might collide. You are better off just importingmy_module
and then accessing what you need from it using regular attribute access (e.g.,my_module.someAttr
), orgetattr
if you need to access its attributes dynamically.My case was a bit different - wanted to dynamically import the constants.py names in each
gameX.__init__.py
module (see below), cause statically importing those would leave them in sys.modules forever (see: this excerpt from Beazley I picked from this related question).Here is my folder structure:
Each
gameX.__init__.py
exports an init() method - so I had initially afrom .constants import *
in all thosegameX.__init__.py
which I tried to move inside the init() method.My first attempt in the lines of:
Failed with the rather cryptic:
I can assure you there are no nested functions in there. Anyway I hacked and slashed and ended up with:
Where in
game.__init__.py
:(for setattr see How can I add attributes to a module at run time? while for getattr How can I import a python module function dynamically? - I prefer to use those than directly access the
__dict__
)This works and it's more general than the approach in the accepted answer cause it allows you to have the hack in one place and use it from whatever module. However I am not really sure it's the best way to implement it - was going to ask a question but as it would be a duplicate of this one I am posting it as an answer and hope to get some feedback. My questions would be:
import *
? even in python 3 ?