5

I'd like to dynamically import various settings and configurations into my python program - what you'd typically do with a .ini file or something similar.

I started with JSON for the config file syntax, then moved to YAML, but really I'd like to use Python. It'll minimize the number of formats and allow me to use code in the config file, which can be convenient.

I hacked up an __import__ based system to allow this using code that looks like:

account_config = __import__(settings.CONFIG_DIR + '.account_name', fromlist=[settings.CONFIG_DIR])

It basically works, but I'm running into all kinds of esoteric problems - eg. if I try to import "test" it picks up some internal python library that's in the python path instead of my test.

So I'm wondering: is using python as the configuration language for a python program viable or am I asking for trouble? Are there examples I can steal from?

4
  • 3
    Django project does almost exactly this. It's common. It's a good idea. Just pick a better name. The library is full of names you cannot use. However, there are an almost infinite number of names that are not in the library. Commented Jan 11, 2012 at 20:17
  • Thanks S.Lott. I ran into the "test" issue almost immediately so it scared me off - I'm concerned there'll be random name clashes that'll cause debugging nightmares in production. Commented Jan 11, 2012 at 20:20
  • They're not "random". They're well documented in the library documentation. Commented Jan 11, 2012 at 20:23
  • I agree that the Python library names are not random, but mine can be. Commented Jan 11, 2012 at 20:49

2 Answers 2

6

One easy way is this.

Your config file assigns a bunch of global variables.

CONFIG = "some string"
ANOTHER = [ "some", "list" ]
MORE = "another value"

You use import all these settings like this

settings = {}
execfile('the_config.py', settings )
settings['CONFIG'] == "some string"

Now your settings dictionary has all of the global variables set.

Sign up to request clarification or add additional context in comments.

1 Comment

Your comment was actually the answer I wanted to accept; I ended up going with the import model above.
5

is using python as the configuration language for a python program viable or am I asking for trouble?

Depends; realize that you're getting a Turing-complete configuration file format with on OS interface. That might raise security issues, so don't do this with config files from an untrusted source.

OTOH, this setup can be very convenient.

Are there examples I can steal from?

Django.

1 Comment

IPython also does this.

Your Answer

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.