Comparing Dictionaries

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Jul 28 02:21:14 CEST 2007


On Fri, 27 Jul 2007 14:11:02 -0500, Kenneth Love wrote:

> The published recipe (based on ConfigParser) did not handle my INI
> files.  I have periods in both the section names and the key names.
> The INI files contents were developed according to an internally
> defined process that other non-Python programs rely on.  The published
> recipe *did not work* with this scenario.

I think you have made a mistake. ConfigParser as published certainly DOES
accept periods in section and option names. It just *works*.

Here's my INI file:

[SECTION.FRED]
option.wilma = 45



And here's how I read it:

>>> import ConfigParser
>>> D = ConfigParser.ConfigParser()
>>> D.read('Desktop/data.ini')
['Desktop/data.ini']
>>> D.sections()
['SECTION.FRED']
>>> D.options('SECTION.FRED')
['option.wilma']
>>> D.getint('SECTION.FRED', 'option.wilma')
45


Even if the existing ConfigParser doesn't do what you want, the right way
to fix the problem is not to recreate the entire module from scratch, but
to subclass it:


import ConfigParser

class MyConfigParser(ConfigParser.ConfigParser):
    # Warning: untested. I haven't even looked at the source code
    # of the original.
    def getint(self, section, option):
        value = super(MyConfigParser, self).getint(section, option)
        return value + 1


(Although, it has to be said... if somebody can subclass ConfigParser so
that writing a modified file doesn't remove comments, I'll be mightily
impressed.)


-- 
Steven.




More information about the Python-list mailing list