Is there a ConfigParser which keeps comments

Gelonida N gelonida at gmail.com
Thu Mar 15 20:34:44 EDT 2012


On 03/15/2012 10:42 PM, Cameron Simpson wrote:
> On 14Mar2012 13:13, Tim Chase <python.list at tim.thechases.com> wrote:
> | On 03/14/12 12:06, Terry Reedy wrote:
> | > On 3/14/2012 6:07 AM, Gelonida N wrote:
> | >> Now I'm looking for a library, which behaves like config parser, but
> | >> with one minor difference.
> | >>
> | >> The write() mehtod should keep existing comments.
> | >
> | > Assuming that you have not overlooked anything, I would just subclass
> | > ConfigParser with an altered write method.
> | 
> | It would require a lot more than that.  It would entail changing 
> | the reading as well so that it preserved the comments as well as 
> | the order of sections & keys, and a way of storing those 
> | associated comments in sequence.  I looked into it a fair while 
> | back and it was a LOT more work than I cared to do for minimal 
> | gain.  I wimped out and just documented it with "If you use the 
> | ability to (re)write a configuration file, it will not keep any 
> | comments or ordering from any original sources."
> 
> A low cost approach might be to patch the file instead of transcribing
> the in-memory state. Not the same semantics, but it would not be too
> hard to add a patch_config(filename, section, setting, value) that read
> the old file and wrote a new one with an adjusted section, ignoring the
> in-memory state (indeed, on that basis the siganture isn't a method but
> a standalone function).
> 
> The logic is easy enough that I even wrote a shell script in 2004 to do
> essentially this:
> 
>   https://bitbucket.org/cameron_simpson/css/src/ef42896872b5/bin/winclauseappend
> 
> One could imagine an efficient python implementation and a ConfigParser
> subclass that patched the file if a setting got changed, or had a .patch
> method to apply particular setting changes as desired.
> 

Agreed, patching is simpler than parsing the file and keeping all the
comment info in the config object.

I will also look at  ConfigObj as suggested by Steven and Karim

If this does what I want, then it's probably less effort to use this
library than patching Configparser.





More information about the Python-list mailing list