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 ?

SilentGhost
322k67 gold badges312 silver badges294 bronze badges
asked Oct 5, 2010 at 15:27

4 Answers 4

1

Try using a bogus 'fromlist' argument.

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

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

answered Oct 5, 2010 at 16:32
Sign up to request clarification or add additional context in comments.

Comments

0
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.

answered Oct 5, 2010 at 15:30

2 Comments

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

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...

answered Oct 5, 2010 at 16:00

Comments

0

I tried the code below and it worked.

Here is my folder structure:

src/
 app.py
 settings/
 __init__.py
 production.py
 sandbox.py

In settings.__init__.py, I wrote:

import os 
settings_module = os.environ.get('APP_SETTINGS')
if not settings_module:
 from .sandbox import *
else:
 exec('from {} import *'.format(settings_module))

If the var env was not set, imports the sandbox module. If was setting, imports the module dynamically.

Hope this helps

answered Oct 11, 2018 at 20:07

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.