Most Pythonic way to store (small) configuration

Chris Angelico rosuav at gmail.com
Wed Aug 5 12:01:51 CEST 2015


On Wed, Aug 5, 2015 at 6:32 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> My own personal feeling is that using code as config is a little
> disquieting. It's a bit of a code smell. Do you really need that much power
> just to allow people to set some configuration settings? Using a Turing
> Complete programming language just to set a bunch of name:value pairs seems
> to be gross overkill.
>
> But on the other hand, config systems do tend to grow in power. People often
> want conditional and computed settings. Rather than invent your own (buggy)
> mini-language to allow conf like this:
>
> if $PLATFORM = 'Windows' set location = 'C:\The Stuff';
> if $PLATFORM = 'Linux' set location = $baselocation + '/thestuff';
>
> using Python seems like a much better idea.

I often have config files where the example is really simple, like this:

https://github.com/Rosuav/LetMeKnow/blob/master/keys_sample.py
https://github.com/Rosuav/Yosemite/blob/master/config.py

but the in-production versions sometimes have a teensy bit more code
in them - maybe an if-expression, maybe pulling something from
os.environ. In both of those cases, any person editing the config file
will also have full power to tamper with the source code, so the
security issue doesn't apply; and apart from requiring quotes around
string values, it's pretty much the level of simplicity you'd get out
of any other config file format. You get comments, you get freedom to
add whitespace anywhere you like (or not add it, if you so desire),
it's great! Right? Well, there is another subtlety, and that's that
there's no error checking. If you duplicate an entry, nobody will
issue even a warning. For small config files, that's fine; but what if
you're editing something the size of postgresql.conf? You can't keep
it all on screen or in your head, and if you simply search the file
for some keyword, would you notice that there are two of them?

So, I'd recommend this if - and ONLY if - the files are normally going
to be small enough to fit on a single page. Otherwise, consider
carefully whether you'd later on want to add error checking like that,
and consider how hard it would be to hack that in.

Drink responsibly.

ChrisA


More information about the Python-list mailing list