Python ConfigParser

configparser is a module that supports (de-)serializing configuration files.

Note that, in Python 2, the module's name was ConfigParser.

The configuration language is based on (but not exactly the same as) the Windows INI file.


Configuration Language

Sections

All options must be set under a section header. Section headers cannot be repeated, or the parser will raise configparser.DuplicateSectionError.

[Section1]
option=1

[Section2]
option=2

Options and Values

Configurations are composed of options and values, both of which are parsed as strings. The option and value parts are delimited by either equals signs (=) or colons (:). Spaces around the delimiter are ignored, but all other spaces are retained in the option and value.

[Section]
foo=1
bar=abc

Options must be set with a value or configparser.ParsingError will be raised. An empty value (i.e. a delimiter with no righthand side value) is valid. In this case, options are set to ''.

[Section]
baz=

This can be altered by setting allow_no_value=True on the parser. In this case, options are set to None.

[Section]
keyword-instruction

Options must be unique within a section or configparser.DuplicateOptionError will be raised.

Defaults

Default options and values can be in a DEFAULT section.

The name of this section can be adjusted by setting the parser's default_section argument or by setting the configparser.DEFAULTSECT constant.

[DEFAULT]
foo = 1

Interpolation

Configuration can be written with variables by setting the parser's interpolation argument, as with interpolation=configparser.BasicInterpolation().

[Section]
user dir   = /Users
my dir = %(my dir)s/me


Usage

import configparser
c = configparser.ConfigParser()
c.read('example.ini')

The configuration API mirrors that of dictionaries.

c.get('Section', 'option')
c.get('Section', 'option', fallback=False)
c['Section']['option']

Sections

Sections of configuration can be accessed with parser['section']. This returns a proxy for the internal data structure. If values are set (or changed) in either the configuration or section, the other also updates.

The configuration section API matches that of dictionaries.

s = c['section']
s.get('option', False)

Helper Methods

c.getint('section', 'option')
c.getfloat('section', 'option')
c.getboolean('section', 'option')

getboolean is particularly useful; it interprets a variety of string values as boolean values: true and false, yes and no, on and off, 1 and 0.

Default Values

Parser defaults are set at creation.

c = configparser.ConfigParser({'foo': 'bar'})


See also

Python configparser module documentation

Python Module of the Day article for configparser


CategoryRicottone

Python/ConfigParser (last edited 2023-06-15 18:40:07 by DominicRicottone)