On Fri, 2010-12-10 at 05:10 -0500, Martin Krizek wrote:
+class SingleConfigParser(ConfigParser.SafeConfigParser):
+ '''This is a subclassed SafeConfigParser. It has several
additional methods
+ serving our needs.
+ '''
+ def read_single(self, filenames):
+ '''This is the same as the read() method, but it parsers only
the first
+ available config file from the list, not all of them.
+ '''
+ if isinstance(filenames, str):
+ filenames = [filenames]
+ for f in filenames:
+ retval = self.read(f)
+ if retval:
+ # file read, don't read any other
+ return retval
+ else:
+ return []
+
+ def get_section(self, section, default_conf={}):
+ '''Read the whole section and convert it into a dictionary
(with string
+ values).
+
+ Args:
+ section -- section of the config to be retrieved
+ default_conf -- default configuration values
+
+ Returns:
+ Dictionary containing retrieved data on success.
+
+ Throws:
+ ConfigParser.NoSectionError -- when no such section exists
+ '''
+ items = dict(self.items(section))
+ retval = default_conf.copy()
+ retval.update(items)
+ return retval
+
+def getbool(string):
+ '''Converts a string into a boolean.
+ Recognizes many usual strings: 1/0, yes/no, true/false,
on/off; also
+ empty strings.
+ Throws ValueError if the string can't be recognized.
+ '''
+ boolean_states = {'1': True, 'yes': True, 'true': True,
'on':
True,
+ '0': False, 'no': False, 'false': False,
'off':
False}
+ if not string:
+ return False
+
+ string = string.lower()
+ if string not in boolean_states:
+ raise ValueError, 'Not a boolean: %s' % string
+ return boolean_states[string]
Everything looks good. Only one comment regarding the getbool() method.
Doesn't SafeConfigParser provide different methods to return a value of
a specific type? For example, getboolean(), getfloat(), getint().
Should we be using (or overloading in the case of getboolean) those
built-in methods instead?
Thanks,
James