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?

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
pdc
  • 2,314
  • 20
  • 28
  • 1
    Exact duplicate here: http://stackoverflow.com/questions/147507/how-does-one-do-the-equivalent-of-import-from-module-with-pythons-import – u0b34a0f6ae Oct 23 '09 at 18:04
  • 1
    Thanks -- I did try to search for it, honest, but when the underscores are stripped off, __import__ is not a very specific search term... :-) – pdc Oct 23 '09 at 18:41

1 Answers1

1

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
  • 85,954
  • 40
  • 175
  • 219
  • 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 Oct 23 '09 at 18:37
  • But the main point is that globals() is the current namespace -- it even says so in the documentation -- but I always vaguely assumed it was the 'top' namespace, which is wrong. – pdc Oct 23 '09 at 18:39