Subclassing ConfigParser

Greg Krohn ask at me.com
Thu Aug 21 12:53:04 EDT 2003


I'm trying to subclass ConfigParser so I can use a custom __read method (the
custom format doesn't conform to RFC 822) when needed. Needless to say, it's
not working as expected.

In the following code, I bind __read_ini to __read and override __read so it
can choose between __read_ini and __read_custom. But it seems that
__read_custom never gets called when I expect it to aways be called. I have
a feeling this has to do with me not entirely understanding magic atributes
and name mangling. Anyone have ideas?


greg



from ConfigParser import ConfigParser

class CustomConfigParser(ConfigParser):
    def __init__(self, defaults=None):
        ConfigParser.__init__(self, defaults)

        #Replace the normal __read with my custom __read
        #while keeping the normal one around if I need it
        self.__read_ini = ConfigParser._ConfigParser__read
        ConfigParser._ConfigParser__read = self.__read

    def __read(self, fp, fpname):
        #Eventually this will decide between __read_custom
        #and __read_ini, etc.
        self.__read_custom(fp, fpname)

    def __read_custom(self, fp, fpname):
        print "__read_custom" #This never gets printed.

cp = CustomConfigParser()
cp.read('config.ini')
print cp.sections()






More information about the Python-list mailing list