reading optional configuration from a file

Ulrich Eckhardt ulrich.eckhardt at dominolaser.com
Thu Nov 24 06:56:42 EST 2011


Hi!

I have a few tests that require a network connection. Typically, the 
target will be localhost on port 20000. However, sometimes these 
settings differ, so I want to be able to optionally set them.

What I'm currently doing is this:

     try:
         from settings import REMOTE_HOST, REMOTE_PORT
     except ImportError:
         REMOTE_HOST = 'localhost'
         REMOTE_PORT = 20000

This works fine. However, there are actually a few more settings that 
can be overridden, so I changed the whole thing to this:

     try:
         from settings import *
         if not 'REMOTE_HOST' in locals():
             REMOTE_HOST = 'localhost'
         if not 'REMOTE_PORT' in locals():
             REMOTE_PORT = 20000
     except ImportError:
         REMOTE_HOST = 'localhost'
         REMOTE_PORT = 20000

Yes, wildcard imports are dangerous, but that's something I don't mind 
actually, this is an internal tool for clueful users. Still, this is 
ugly, since the defaults are stored redundantly, so I went to this variant:

     REMOTE_HOST = 'localhost'
     REMOTE_PORT = 20000
     try:
         from settings import *
     except ImportError:
         pass

Now, in order to avoid ambiguities, I thought about using relative 
imports, but there I'm stomped because wildcard imports are not 
supported for relative imports, it seems.


How would you do it? Any other suggestions?

Cheers!

Uli



More information about the Python-list mailing list