Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python as the config language for a Python program

Tags:

python

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?

like image 774
Parand Avatar asked Jan 11 '12 20:01

Parand


2 Answers

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.

like image 157
S.Lott Avatar answered Oct 11 '22 16:10

S.Lott


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.

like image 40
Fred Foo Avatar answered Oct 11 '22 16:10

Fred Foo