reading optional configuration from a file

U

Ulrich Eckhardt

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
 
M

Matt Joiner

   REMOTE_HOST = 'localhost'    REMOTE_PORT = 20000    try:
from .settings import *    except ImportError:        pass
This works? If you're using an old version of Python you may need to
mess about with __future__.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,781
Messages
2,569,615
Members
45,294
Latest member
LandonPigo

Latest Threads

Top