Python Forum
case transparent names in configpaser - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: case transparent names in configpaser (/thread-30053.html)



case transparent names in configpaser - Skaperen - Oct-01-2020

is there a way to customize configparser to disable case insensitive aspect of INI files. i only need case transparency where sections and options i add retain the same case i added them with so that the re-created file has them. it turns out that writing the INI back out to a file changes all sections and all options to lower case even if i change nothing.


RE: case transparent names in configpaser - bowlofred - Oct-01-2020

You can override optionxform. There's a section in the docs about doing this.

Quote:ConfigParser.optionxform(option)

This method transforms option names on every read, get, or set operation. The default converts the name to lowercase. This also means that when a configuration file gets written, all keys will be lowercase. Override this method if that’s unsuitable. For example:

>>> config = """
... [Section1]
... Key = Value
...
... [Section2]
... AnotherKey = Value
... """
>>> typical = configparser.ConfigParser()
>>> typical.read_string(config)
>>> list(typical['Section1'].keys())
['key']
>>> list(typical['Section2'].keys())
['anotherkey']
>>> custom = configparser.RawConfigParser()
>>> custom.optionxform = lambda option: option
>>> custom.read_string(config)
>>> list(custom['Section1'].keys())
['Key']
>>> list(custom['Section2'].keys())
['AnotherKey']



RE: case transparent names in configpaser - Skaperen - Oct-01-2020

can you be more explicit in pointing to the docs? i don't see it. or maybe the PDF doc page number.


RE: case transparent names in configpaser - bowlofred - Oct-01-2020

There doesn't seem to be an id tag for the section I quoted in the configparser docs. Search for "ConfigParser.optionxform(option)" on that page. (or any of the other places that "optionx" is mentioned).


RE: case transparent names in configpaser - Skaperen - Oct-02-2020

i think this was over explained. it simply is:

the attribute of the configparser object named "optionxform" is where the configparser code gets a reference to the function it calls to change option names and section names to lower case. by replacing this reference, you can substitute your own function to make whatever change you want to have made (or none at all). your function should be idempotent as names could be passed through many times.

so, for my case i could just do myparser.optionxform = str.