If it won't be simple, it simply won't be. [Hire me, source code] by Miki Tebeka, CEO, 353Solutions

Thursday, May 18, 2006

Using Python Syntax in Configuration Files

As a rule it thumb, it's best to place as many configuration options in a configuration file. This way you don't need to edit/compile the code to change its behavior.

However writing a parser for configuration files takes time, and the standard ones (.ini and .xml) have their limitations. Lucky for us each Python program comes with the full interpreter bundled. We can do stuff like:

# settings.py
from sys import platform

if platform == "win32":
APP_HOME = "c:\\my_cool_app"
APP_HOME = "/opt/my_cool_app"

Then using __import__ in our application we can load the configuration file and parse it without a sweat:

# my_cool_app.py
settings = __import__("settings.py")
print settings.APP_HOME

To view this approach taken to extreme, have a look at http://www.unixreview.com/documents/s=9133/ur0404e/
Post a Comment

Blog Archive