views:

208

answers:

4

I've noticed with my source control that the content of the output files generated with ConfigParser is never in the same order. Sometimes sections will change place or options inside sections even without any modifications to the values.

Is there a way to keep things sorted in the configuration file so that I don't have to commit trivial changes every time I launch my application?

+3  A: 

No. The ConfigParser library writes things out in dictionary hash order. (You can see this if you look at the source code.) There are replacements for this module that do a better job.

I will see if I can find one and add it here.

http://www.voidspace.org.uk/python/configobj.html#introduction is the one I was thinking of. It's not a drop-in replacement, but it is very easy to use.

Christopher
A: 

ConfigParser is based on the ini file format, who in it's design is supposed to NOT be sensitive to order. If your config file format is sensitive to order, you can't use ConfigParser. It may also confuse people if you have an ini-type format that is sensitive to the order of the statements...

Lennart Regebro
It is still helpful to have the items come out in the same order if you are versioning the results and want to see reasonable-looking diffs from version to version.
scrible
Ah, right. I completely missed that you were creating files. My bad. It's configPARSER after all. ;)
Lennart Regebro
+2  A: 

Looks like this was fixed in Python 3.1 with the introduction of ordered dictionaries:

The standard library now supports use of ordered dictionaries in several modules. The configparser module uses them by default. This lets configuration files be read, modified, and then written back in their original order.

Alexander Ljungberg
Doh. Useful, but have to wait some years before we can use it in production...
pihentagy
+2  A: 

This answer to a similar question gives some suggestions on how to accomplish sorted output in Python 2.

Don Kirkby