ConfigParser subclass problem

Matimus mccredie at gmail.com
Fri Sep 26 16:42:27 EDT 2008


On Sep 26, 12:56 pm, Strato <pyt... at p0w.org> wrote:
> Hi folks,
>
> I think I do something wrong, but I don't see why it doesn't work, so I
> will explain:
>
> I've searched in the list archive and found this thread, that explain
> exactly what I want to have: the options strings returned by
> ConfigParser without being lower cased.
>
> I tryed to reproduce this, by subclassing the SafeConfigParser class,
> like this:
>
> * in my main script:
>
> from MyConfigParser import *
>
> * in the MyConfigParser.py file:
> from ConfigParser import SafeConfigParser
>
> class MyConfigParser(SafeConfigParser):
>     def optionxform(self, optionstr):
>         print "Called the modified version of the class"
>         return optionstr
>
> then, when I run the script, every time a calls to my own class is done,
> the print statment is shown in the console, so this may work, but when I
> use the .items() method of the class, I got a lower cased result !
>
> (In my test, using the .items() method is my only try to test the new class)
>
> Does anybody has an idea of what I'm doing wrong ?
>
> Thanks,
> Strato

I don't know what you are doing wrong. It works just fine for me:

[code]
from ConfigParser import SafeConfigParser
from StringIO import StringIO

class MyConfigParser(SafeConfigParser):
    def optionxform(self, optionstr):
        print "Called the modified version of the class"
        return optionstr

def main():
    contents = StringIO("""
[Section1]
Foo=Bar
Bar=Baz
Spam=Eggs
[Section2]
Hello=World
""")

    raw_parser = SafeConfigParser()
    raw_parser.readfp(contents)
    print "Using SafeConfigParser Section1"
    for item in raw_parser.items("Section1"):
        print item
    print "Using SafeConfigParser Section2"
    for item in raw_parser.items("Section2"):
        print item

    contents.seek(0)
    my_parser = MyConfigParser()
    my_parser.readfp(contents)
    print
    print "Using MyConfigParser Section1"
    for item in my_parser.items("Section1"):
        print item
    print "Using MyConfigParser Section2"
    for item in my_parser.items("Section2"):
        print item

if __name__ == "__main__":
    main()
[/code]

Produces the output:

Using SafeConfigParser Section1
('foo', 'Bar')
('bar', 'Baz')
('spam', 'Eggs')
Using SafeConfigParser Section2
('hello', 'World')
Called the modified version of the class
Called the modified version of the class
Called the modified version of the class
Called the modified version of the class

Using MyConfigParser Section1
('Foo', 'Bar')
('Bar', 'Baz')
('Spam', 'Eggs')
Using MyConfigParser Section2
('Hello', 'World')


Matt



More information about the Python-list mailing list