[Tutor] Re: Config Files (original) (raw)

Andrei project5 at redrival.net
Wed Jul 7 19:56:28 CEST 2004


Karthikesh Raju wrote on Wed, 7 Jul 2004 14:03:14 +0300:

Thankx Andrei for your suggestion. i have now altered the config files as

[user] K = 8 [userless] K1 = 2 etc etc and loaded then using configParser module, and unpacked the dictionaries so now i will have two dictionaries user, userless with keys K and K1, but the keys are converted to lowercase, which i dont want, so a key like simulateK becomes simulatek.

Well, the ConfigParser is case insensitive, so it doesn't matter if you ask it for 'simulateK' or 'simulatek'. This is generally a good thing (I'm not very fond of case sensitivity, not even in Python), but if you do need it, it seems quite easy to implement.

Why is this so? How do i solve it?

If you look at the source code of ConfigParser.py, you'll see that ConfigParser inherits from RawConfigParser and RawConfigParser has a method "optionxform" which converts a string to its lowercase equivalent. It's called whenever you ask the config parser for an option. It's easy to get around it by subclassing ConfigParser and overriding this one method:

from ConfigParser import ConfigParser class CaseConfigParser(ConfigParser): ... """A case sensitive configparser.""" ... def optionxform(self, optionstr): ... # used to say: return optionstr.lower() ... return optionstr ...
cp = CaseConfigParser() cp.addsection('section 1') cp.addsection('Section 1') cp.sections() ['section 1', 'Section 1'] cp.set('section 1', 'first entry', '5') cp.set('Section 1', 'second entry', 'Abc') cp.set('Section 1', 'Second entry', 'deF') cp.get('Section 1', 'Second entry') 'deF' cp.get('Section 1', 'second entry') 'Abc'

With regards to the the int problem i used string.atof in a try-except loop. Is this fine?

try-except is fine, string.atof is not really. You should avoid the string module, it's deprecated. It's only useful if you need one of the constants contained within. Use the built-in functions instead, like int() and float() depending on whather you need integers or floating-point numbers.

-- Yours,

Andrei

===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP.



More information about the Tutor mailing list