Welcome to configparser documentation!

Configuration file parser.

A configuration file consists of sections, lead by a “[section]” header, and followed by “name: value” entries, with continuations and such in the style of RFC 822.

Intrinsic defaults can be specified by passing them into the ConfigParser constructor as a dictionary.

class:

ConfigParser – responsible for parsing a list of

configuration files, and managing the parsed database.

methods:

__init__(defaults=None, dict_type=_default_dict, allow_no_value=False,

delimiters=(‘=’, ‘:’), comment_prefixes=(‘#’, ‘;’), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=’DEFAULT’, interpolation=<unset>, converters=<unset>):

Create the parser. When `defaults’ is given, it is initialized into the dictionary or intrinsic defaults. The keys must be strings, the values must be appropriate for %()s string interpolation.

When `dict_type’ is given, it will be used to create the dictionary objects for the list of sections, for the options within a section, and for the default values.

When `delimiters’ is given, it will be used as the set of substrings that divide keys from values.

When `comment_prefixes’ is given, it will be used as the set of substrings that prefix comments in empty lines. Comments can be indented.

When `inline_comment_prefixes’ is given, it will be used as the set of substrings that prefix comments in non-empty lines.

When strict is True, the parser won’t allow for any section or option duplicates while reading from a single source (file, string or dictionary). Default is True.

When `empty_lines_in_values’ is False (default: True), each empty line marks the end of an option. Otherwise, internal empty lines of a multiline option are kept as part of the value.

When `allow_no_value’ is True (default: False), options without values are accepted; the value presented for these is None.

When default_section’ is given, the name of the special section is named accordingly. By default it is called `”DEFAULT”`` but this can be customized to point to any other valid section name. Its current value can be retrieved using the parser_instance.default_section attribute and may be modified at runtime.

When interpolation is given, it should be an Interpolation subclass instance. It will be used as the handler for option value pre-processing when using getters. RawConfigParser object s don’t do any sort of interpolation, whereas ConfigParser uses an instance of BasicInterpolation. The library also provides a zc.buildbot inspired ExtendedInterpolation implementation.

When converters is given, it should be a dictionary where each key represents the name of a type converter and each value is a callable implementing the conversion from string to the desired datatype. Every converter gets its corresponding get*() method on the parser object and section proxies.

sections()

Return all the configuration section names, sans DEFAULT.

has_section(section)

Return whether the given section exists.

has_option(section, option)

Return whether the given option exists in the given section.

options(section)

Return list of configuration options for the named section.

read(filenames, encoding=None)

Read and parse the iterable of named configuration files, given by name. A single filename is also allowed. Non-existing files are ignored. Return list of successfully read files.

read_file(f, filename=None)

Read and parse one configuration file, given as a file object. The filename defaults to f.name; it is only used in error messages (if f has no `name’ attribute, the string `<???>’ is used).

read_string(string)

Read configuration from a given string.

read_dict(dictionary)

Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. Values are automatically converted to strings.

get(section, option, raw=False, vars=None, fallback=_UNSET)

Return a string value for the named option. All % interpolations are expanded in the return values, based on the defaults passed into the constructor and the DEFAULT section. Additional substitutions may be provided using the `vars’ argument, which must be a dictionary whose contents override any pre-existing defaults. If `option’ is a key in `vars’, the value from `vars’ is used.

getint(section, options, raw=False, vars=None, fallback=_UNSET)

Like get(), but convert value to an integer.

getfloat(section, options, raw=False, vars=None, fallback=_UNSET)

Like get(), but convert value to a float.

getboolean(section, options, raw=False, vars=None, fallback=_UNSET)

Like get(), but convert value to a boolean (currently case insensitively defined as 0, false, no, off for False, and 1, true, yes, on for True). Returns False or True.

items(section=_UNSET, raw=False, vars=None)

If section is given, return a list of tuples with (name, value) for each option in the section. Otherwise, return a list of tuples with (section_name, section_proxy) for each section, including DEFAULTSECT.

remove_section(section)

Remove the given file section and all its options.

remove_option(section, option)

Remove the given option from the given section.

set(section, option, value)

Set the given option.

write(fp, space_around_delimiters=True)

Write the configuration state in .ini format. If `space_around_delimiters’ is True (the default), delimiters between keys and values are surrounded by spaces.

exception configparser.NoSectionError(section)

Bases: configparser.Error

Raised when no section matches a requested option.

exception configparser.DuplicateOptionError(section, option, source=None, lineno=None)

Bases: configparser.Error

Raised by strict parsers when an option is repeated in an input source.

Current implementation raises this exception only when an option is found more than once in a single file, string or dictionary.

exception configparser.DuplicateSectionError(section, source=None, lineno=None)

Bases: configparser.Error

Raised when a section is repeated in an input source.

Possible repetitions that raise this exception are: multiple creation using the API or in strict parsers when a section is found more than once in a single input file, string or dictionary.

exception configparser.NoOptionError(option, section)

Bases: configparser.Error

A requested option was not found.

exception configparser.InterpolationError(option, section, msg)

Bases: configparser.Error

Base class for interpolation-related exceptions.

exception configparser.InterpolationDepthError(option, section, rawval)

Bases: configparser.InterpolationError

Raised when substitutions are nested too deeply.

exception configparser.InterpolationMissingOptionError(option, section, rawval, reference)

Bases: configparser.InterpolationError

A string substitution required a setting which was not available.

exception configparser.InterpolationSyntaxError(option, section, msg)

Bases: configparser.InterpolationError

Raised when the source text contains invalid syntax.

Current implementation raises this exception when the source text into which substitutions are made does not conform to the required syntax.

exception configparser.ParsingError(source=None, filename=None)

Bases: configparser.Error

Raised when a configuration file does not follow legal syntax.

append(lineno, line)
property filename

Deprecated, use `source’.

exception configparser.MissingSectionHeaderError(filename, lineno, line)

Bases: configparser.ParsingError

Raised when a key-value pair is found before any section header.

class configparser.ConfigParser(defaults=None, dict_type=<class 'collections.OrderedDict'>, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section='DEFAULT', interpolation=<object object>, converters=<object object>)

Bases: configparser.RawConfigParser

ConfigParser implementing interpolation.

add_section(section)

Create a new section in the configuration. Extends RawConfigParser.add_section by validating if the section name is a string.

set(section, option, value=None)

Set an option. Extends RawConfigParser.set by validating type and interpolation syntax on the value.

class configparser.SafeConfigParser(*args, **kwargs)

Bases: configparser.ConfigParser

ConfigParser alias for backwards compatibility purposes.

class configparser.RawConfigParser(defaults=None, dict_type=<class 'collections.OrderedDict'>, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section='DEFAULT', interpolation=<object object>, converters=<object object>)

Bases: collections.abc.MutableMapping

ConfigParser that does not do interpolation.

BOOLEAN_STATES = {'0': False, '1': True, 'false': False, 'no': False, 'off': False, 'on': True, 'true': True, 'yes': True}
NONSPACECRE = re.compile('\\S')
OPTCRE = re.compile('\n (?P<option>.*?) # very permissive!\n \\s*(?P<vi>=|:)\\s* # any number of space/tab,\n # followed by any of t, re.VERBOSE)
OPTCRE_NV = re.compile('\n (?P<option>.*?) # very permissive!\n \\s*(?: # any number of space/tab,\n (?P<vi>=|:)\\s* # optionally followed , re.VERBOSE)
SECTCRE = re.compile('\n \\[ # [\n (?P<header>[^]]+) # very permissive!\n \\] # ]\n ', re.VERBOSE)
add_section(section)

Create a new section in the configuration.

Raise DuplicateSectionError if a section by the specified name already exists. Raise ValueError if name is DEFAULT.

property converters
defaults()
get(section, option, *, raw=False, vars=None, fallback=<object object>)

Get an option value for a given section.

If `vars’ is provided, it must be a dictionary. The option is looked up in `vars’ (if provided), `section’, and in `DEFAULTSECT’ in that order. If the key is not found and `fallback’ is provided, it is used as a fallback value. `None’ can be provided as a `fallback’ value.

If interpolation is enabled and the optional argument `raw’ is False, all interpolations are expanded in the return values.

Arguments `raw’, `vars’, and `fallback’ are keyword only.

The section DEFAULT is special.

getboolean(section, option, *, raw=False, vars=None, fallback=<object object>, **kwargs)
getfloat(section, option, *, raw=False, vars=None, fallback=<object object>, **kwargs)
getint(section, option, *, raw=False, vars=None, fallback=<object object>, **kwargs)
has_option(section, option)

Check for the existence of a given option in a given section. If the specified `section’ is None or an empty string, DEFAULT is assumed. If the specified `section’ does not exist, returns False.

has_section(section)

Indicate whether the named section is present in the configuration.

The DEFAULT section is not acknowledged.

items(section=<object object>, raw=False, vars=None)

Return a list of (name, value) tuples for each option in a section.

All % interpolations are expanded in the return values, based on the defaults passed into the constructor, unless the optional argument `raw’ is true. Additional substitutions may be provided using the `vars’ argument, which must be a dictionary whose contents overrides any pre-existing defaults.

The section DEFAULT is special.

options(section)

Return a list of option names for the given section name.

optionxform(optionstr)
popitem()

Remove a section from the parser and return it as a (section_name, section_proxy) tuple. If no section is present, raise KeyError.

The section DEFAULT is never returned because it cannot be removed.

read(filenames, encoding=None)

Read and parse a filename or an iterable of filenames.

Files that cannot be opened are silently ignored; this is designed so that you can specify an iterable of potential configuration file locations (e.g. current directory, user’s home directory, systemwide directory), and all existing configuration files in the iterable will be read. A single filename may also be given.

Return list of successfully read files.

read_dict(dictionary, source='<dict>')

Read configuration from a dictionary.

Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order.

All types held in the dictionary are converted to strings during reading, including section names, option names and keys.

Optional second argument is the `source’ specifying the name of the dictionary being read.

read_file(f, source=None)

Like read() but the argument must be a file-like object.

The `f’ argument must be iterable, returning one line at a time. Optional second argument is the `source’ specifying the name of the file being read. If not given, it is taken from f.name. If `f’ has no `name’ attribute, `<???>’ is used.

read_string(string, source='<string>')

Read configuration from a given string.

readfp(fp, filename=None)

Deprecated, use read_file instead.

remove_option(section, option)

Remove an option.

remove_section(section)

Remove a file section.

sections()

Return a list of section names, excluding [DEFAULT]

set(section, option, value=None)

Set an option.

write(fp, space_around_delimiters=True)

Write an .ini-format representation of the configuration state.

If `space_around_delimiters’ is True (the default), delimiters between keys and values are surrounded by spaces.

class configparser.Interpolation

Bases: object

Dummy interpolation that passes the value through with no changes.

before_get(parser, section, option, value, defaults)
before_read(parser, section, option, value)
before_set(parser, section, option, value)
before_write(parser, section, option, value)
class configparser.BasicInterpolation

Bases: configparser.Interpolation

Interpolation as implemented in the classic ConfigParser.

The option values can contain format strings which refer to other values in the same section, or values in the special default section.

For example:

something: %(dir)s/whatever

would resolve the “%(dir)s” to the value of dir. All reference expansions are done late, on demand. If a user needs to use a bare % in a configuration file, she can escape it by writing %%. Other % usage is considered a user error and raises `InterpolationSyntaxError’.

before_get(parser, section, option, value, defaults)
before_set(parser, section, option, value)
class configparser.ExtendedInterpolation

Bases: configparser.Interpolation

Advanced variant of interpolation, supports the syntax used by `zc.buildout’. Enables interpolation between sections.

before_get(parser, section, option, value, defaults)
before_set(parser, section, option, value)
class configparser.LegacyInterpolation

Bases: configparser.Interpolation

Deprecated interpolation used in old versions of ConfigParser. Use BasicInterpolation or ExtendedInterpolation instead.

before_get(parser, section, option, value, vars)
before_set(parser, section, option, value)
class configparser.SectionProxy(parser, name)

Bases: collections.abc.MutableMapping

A proxy for a single section from a parser.

get(option, fallback=None, *, raw=False, vars=None, _impl=None, **kwargs)

Get an option value.

Unless fallback is provided, None will be returned if the option is not found.

property name
property parser
class configparser.ConverterMapping(parser)

Bases: collections.abc.MutableMapping

Enables reuse of get*() methods between the parser and section proxies.

If a parser class implements a getter directly, the value for the given key will be None. The presence of the converter name here enables section proxies to find and use the implementation on the parser class.

GETTERCRE = re.compile('^get(?P<name>.+)$')

Indices and tables