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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With