Subclassing ConfigParser
Greg Krohn
ask at me.com
Sat Aug 23 21:58:42 EDT 2003
"Michael Amrhein" <michael.amrhein at t-online.de> wrote in message
news:3F4621AC.8050002 at t-online.de...
> Hi Greg,
> are you sure you have a file 'config.ini' in your current working
> directory? ConfigParser is silently ignoring files which cannot be
> opened, so that _read is not called!
I was getting a ParsingError that showed the line it was choking on, so I
know it was finding the file.
>
> BTW, you did not mention the Python version you are using. In Python 2.3
> the method you overwrite is named '_read', not '__read' (so there is no
> name mangling). This is one drawback of overwriting "private" methods,
> when the author renames or removes them, your code is broken.
I _was_ using ActivePython 2.2 (2.3 isn't out yet). I downloaded the 2.3
regular distro last night because I read ConfigParser was cleaned up, but I
haven't had time to mess around with it much.
> Anyway, your method of overwriting the method is a bit complicated . You
> can do it much easier: just overwrite _read and call the original method
> when appropriate:
>
> class CustomConfigParser(ConfigParser):
> def __init__(self, defaults=None):
> ConfigParser.__init__(self, defaults)
> def _read(self, fp, fpname):
> if ... # your criteria for custom ini
> then return self._read_custom(fp, fpname)
> else return ConfigParser._read(self, fp, fpname)
>
> def _read_custom(self, fp, fpname):
> ...
>
> Michael
Yes, this is great! Everything is working as expected now. Originally I was
expecting code like yours to work in 2.2 and when it didn't I tried all
sorts of elaborate hacks. What a mess. Thank you very much for your reply.
greg
More information about the Python-list
mailing list