Dealing with config files what's the options

Dave Brueck dave at pythonapocrypha.com
Fri Feb 25 17:02:04 EST 2005


Jorgen Grahn wrote:
> On Tue, 22 Feb 2005 20:38:28 -0500, Tom Willis <tom.willis at gmail.com> wrote:
> 
>>How are the expert pythoneers dealing with config files?
> 
> ...
> 
>>Any ideas?
> 
> 
> How about writing them in Python?

Depending on who will be editing the config files, this can be a great approach.

At the simplest level, a config.py file like this is so easy to use:

# Net settings
timeoutSec = 5.3
maxConnections = 3

# Other stuff
foo = 'bar'

This type of a format is easy to use for just about anybody who has ever had to 
use config files before. What's nice is that the code to use it is 
straightforward too:

import config
conn = config.maxConnections
...

A few times I've tried to use accessor functions to ensure that the values are 
present or valid or whatever, but I stopped doing that because in practice it's 
just not needed (again, for users who are familiar with the concept of config 
files).

A slightly more elaborate approach gives you full structure:

class Net:
     maxConnections = 12

class System:
     class Logging:
         root = '/var/logs'

This prevents individual setting names from getting unwieldy, and the code that 
uses it can be pretty readable too:

logRoot = config.System.Logging.root

or, if there are lots of retrievals to do:

Logging = config.System.Logging
logRoot = Logging.root
... etc ...

Using classes asks a little bit more of the users (they can break it a little 
more easily), but again, in practice it really hasn't been a problem at all.

-Dave



More information about the Python-list mailing list