Noob confused by ConfigParser defaults

Peter Otten __peter__ at web.de
Mon Feb 20 04:45:12 EST 2017


Ian Pilcher wrote:

> I am trying to use ConfigParser for the first time (while also writing
> my first quasi-serious Python program).  Assume that I want to parse a
> a configuration file of the following form:
> 
>    [section-1]
>    option-1 = value1
>    option-2 = value2
> 
>    [section-2]
>    option-1 = value3
>    option-2 = value4
> 
> How do a set a default for option-1 *only* in section-1?

You can provide a default value in your code with

parser = configparser.ConfigParser()
parser.read(configfile)
value = parser.get("section-1", "option-1", fallback="default value") 

Or you can invent your own convention that the default values for 
"section-1" are found in "section-1-defaults", and then look it up with a 
small helper function:

$ cat cpdemo.ini
[section-1-defaults]
option-2=default2

[section-1]
option-1 = value1

[section-2]
option-1 = value2
$ cat cpdemo.py
import configparser

parser = configparser.ConfigParser()
parser.read("cpdemo.ini")

def get(section, option, **kw):
    try:
        return parser.get(section, option)
    except configparser.NoOptionError:
        try:
            return parser.get(section + "-defaults", option, **kw)
        except (configparser.NoSectionError, configparser.NoOptionError):
            pass
        raise

for section in ["section-1", "section-2"]:
    for option in ["option-1", "option-2"]:
        value  = get(section, option, fallback="#missing")
        print("{}/{} = {}".format(section, option, value))
$ python3 cpdemo.py 
section-1/option-1 = value1
section-1/option-2 = default2
section-2/option-1 = value2
section-2/option-2 = #missing





More information about the Python-list mailing list