tags:

views:

253

answers:

1

I want to replace settings.py in my Django system with a module implemented as a directory settings containing __init__.py. This will try to import a module named after the server, thus allowing for per-server settings.

If I don't know the name of a module before I import it then I can't use the import keyword but must instead use the __import__ function. But this does not add the contents of the module to the settings module. I need the equivalent of from MACHINE_NAME import *. Or I need a way to iterate over vars(m) (where m is the loaded module) and add them to the current namespace. But I can't work out how to refer to the current namespace in order to make the assignment. In other words, I can't use setattr(x, ..) or modify x.__dict__, because I don't know what to use for x.

I can't think of much else to try now apart from using exec. This seems a little feeble to me. Am I missing some aspect of Pythonic introspection that would allow me to manipulate the current scope while still in it?

+1  A: 

For similar situation where based on lang setting I import different messages in messages.py module it is something like

# set values in current namespace
for name in vars(messages):
    v = getattr(messages, name)
    globals()[name] = v

Btw why do you want to create a package for settings.py? whatever you want to do can be done in settings.py directly?

Anurag Uniyal
The main thing is to keep the per-machine configuration files in their own directories so the don't clutter up the rest of the app. Since there is going to be a directory involved either way it seemed reasonable to put __init__.py there...
pdc
But the main point is that globals() is the current namespace -- it even says so in the documentation <http://docs.python.org/library/functions.html#globals> -- but I always vaguely assumed it was the 'top' namespace, which is wrong.
pdc