views:

352

answers:

2

Hi, I have a config file that I read using the RawConfigParser in the standard ConfigParser library. My config file has a [DEFAULT] section followed by a [specific] section. When I loop through the options in the [specific] section, it includes the ones under [DEFAULT], which is what is meant to happen.

However, for reporting I wanted to know whether the option had been set in the [specific] section or in [DEFAULT]. Is there any way of doing that with the interface of RawConfigParser, or do I have no option but to parse the file manually? (I have looked for a bit and I'm starting to fear the worst ...)

For example

[DEFAULT]

name = a

surname = b

[SECTION]

name = b

age = 23

How do you know, using RawConfigParser interface, whether options name & surname are loaded from section [DEFAULT] or section [SECTION]?

(I know that [DEFAULT] is meant to apply to all, but you may want to report things like this internally in order to work your way through complex config files)

thanks!

A: 

Doesn't RawConfigParser.has_option(section, option) do the job?

extraneon
unfortunately no, in my example:cfg.has_option('SECTION','surname') would return true, but surname is actually defined in defaults, and only there
+1  A: 

Given this configuration file:

[DEFAULTS]
name = a
surname = b

[Section 1]
name  = section 1 name
age = 23
#we should get a surname value from defaults

[Section 2]
name = section 2 name
surname = section 2 surname
age = 24

Here's a program that can understand that Section 1 is using the default surname property.

import ConfigParser

parser = ConfigParser.RawConfigParser()
parser.read("config.ini")
#Do your normal config processing here
#When it comes time to audit default vs. explicit,
#clear the defaults
parser.defaults = {}
#Now you will see which options were explicitly defined
print parser.options("Section 1")
print parser.options("Section 2")

And here's the output:

['age', 'name']
['age', 'surname', 'name']
Peter Lyons
Thanks, thats' what I was looking for, actually it's very logical, should have thought of it myself :)