Default Section Values in ConfigParser

Fuzzyman fuzzyman at gmail.com
Wed Mar 1 13:56:17 EST 2006


mwt wrote:
> I want to set default values for a ConfigParser. So far, its job is
> very small, so there is only one section heading, ['Main']. Reading the
> docs, I see that in order to set default values in a ConfigParser, you
> initialize it with a dictionary or defaults. However, I'm not quite
> sure of the syntax to add the section headings in to the dictionary of
> defaults. For now, I'm doing it like this:
>
>         default_values = {'username' : 'put username here',
>                                 'teamnumber': 'team number here',
>                                 'update_interval' : 'update interval'}
>         self.INI = ConfigParser.ConfigParser(default_values)
>         self.INI.add_section('Main')
>
> This works, but clearly won't last beyond the adding of a second
> section. What is the correct way to initialize it with a full
> dictionary of defaults, including section names?
>

An alternative approach is to use `ConfigObj
<http://www.voidspace.org.uk/python/configobj.html>`_. It has two ways
of specifying default values.

The first way is to provide a configspec. This is a schema (that looks
very like a config file itself) that specifies the type (and paramater
bounds if you want) for each member. It can also include a default
value.

Simpler (although without the benefit of validation and type
conversion) is to use the ``merge`` method which is a recursive update.
(Although for config files that are a maximum of one section deep, the
dictionary method ``update`` will do the same job).

         default_values = {'username' : 'put username here',
                                 'teamnumber': 'team number here',
                                 'update_interval' : 'update interval'}
         user_values = ConfigObj(filename)
         cfg = ConfigObj(default_values)
         cfg.merge(user_values)

Note that for a config file with only a few values in it, ConfigObj
doesn't force you to use a section if it's not needed. To put your
default values into a 'Main' section you would actually do :

         default_values = { 'Main': {'username' : 'put username here',
                                 'teamnumber': 'team number here',
                                 'update_interval' : 'update interval'}
}
         #
         user_values = ConfigObj(filename)
         cfg = ConfigObj(default_values)
         cfg.merge(user_values)

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml


> Thanks.




More information about the Python-list mailing list