tags:

views:

56

answers:

3

I have lots of

from myproject.settings import param1
from myproject.settings import ...

scattered all over my project.

Upon startup, I would like to load different "settings" module according to env var (for example export SETTINGS=myproject.settings2)

I tried to put in the myproject.__init__.py someting like

module_name =  os.environ['SETTINGS']
m=__import__(module_name)
settings = m

but it won't work.

from myproject.settings import *
ImportError: No module named settings

How can this be achieved ?

A: 
settings = __import__(os.environ['SETTINGS'])

but it won't work.

Why? Your approach is the right one. As example, Django does this the same way.

leoluk
I don't know I do from myproject.settings import * and get ImportError: No module named settings
bugspy.net
`__import__` imports the module, just access it by the variable you assigned it to; `settings.SOME_SETTING = True`
leoluk
A: 

You could try to add the absolute path of myproject.settings to PYTHONPATH like so:

PYTHONPATH=$PYTHONPATH:$HOME/myproject/settings/ export PYTHONPATH

Now you could keep this in ~/.bashrc (assuming UNIX env). This way whenever you open a new terminal this path is added to PYTHONPATH. i.e. python interpretor would add this path to it's like of paths to look for while importing a module.

Now whichever path you are simply type import settings & since myproject/settings is present python would load settings file.

Hope this helps...

MovieYoda
+1  A: 

Try using a bogus 'fromlist' argument.

mymodule = __import__(mod, fromlist=['a'])

It's worked for me before in situations similar to yours.

jonesy
Thanks. This answer saved me :)
bugspy.net