Differences between revisions 1 and 6 (spanning 5 versions)
Revision 1 as of 2020-03-05 14:45:26
Size: 1341
Comment:
Revision 6 as of 2023-03-01 15:28:08
Size: 3380
Comment:
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
= ConfigParser = = Python ConfigParser =
Line 3: Line 3:
Python has an excessive number of file parsers, especially given the PyPI. But there is just one standard library package that offers a configuration parser--`configparser`. The syntax expected by this parser is a conglomeration of many standards, and the parser has several large opt-in features. '''`configparser`''' is a module for parsing configuration files. The parser is '''`configparser.ConfigParser`'''.

In Python 2, the module's name was `ConfigParser` (mirroring the parser class).

Until Python 3.11 added `tomllib`, `configparser.ConfigParser` was the only built-in configuration file parser.

The configuration language expected by this parser is a conglomeration of many standards, but roughly based on Window's `INI` files.

<<TableOfContents>>

----
Line 7: Line 17:
== Syntax and Syntax Errors == == Configuration Language ==
Line 13: Line 23:
All options must be set under a section header. Section headers cannot be repeated, or the parser will raise `configparser.DuplicateSectionError`. All options must be set under a '''section header'''. Section headers cannot be repeated, or the parser will raise `configparser.DuplicateSectionError`.
Line 25: Line 35:
=== Options === === Options and Values ===
Line 27: Line 37:
Options and values are parsed as strings. The Option and value is delimited by either equals signs (`=`) or colonos (`:`). Spaces around the delimiter are ignored, but all other spaces are retained in the option and value. Options must be set with a value, even if it is empty. 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.
Line 33: Line 43:
}}}

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]
Line 36: Line 52:
If the parser is created with `allow_no_value=True`, options without values are allowed. When gotten, they return `None`. Otherwise, these options will raise `configparser.ParsingError`. This can be altered by setting `allow_no_value=True` on the parser. In this case, options are set to `None`.
Line 43: Line 59:
Options must be unique within a section. Repeated settings will raise `configparser.DuplicateOptionError`. Options must be unique within a section or `configparser.DuplicateOptionError` will be raised.
Line 47: Line 63:
== Default Values == === 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 ===

[[https://docs.python.org/3/library/configparser.html|Python configparser module documentation]]

Python ConfigParser

configparser is a module for parsing configuration files. The parser is configparser.ConfigParser.

In Python 2, the module's name was ConfigParser (mirroring the parser class).

Until Python 3.11 added tomllib, configparser.ConfigParser was the only built-in configuration file parser.

The configuration language expected by this parser is a conglomeration of many standards, but roughly based on Window's INI files.


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


CategoryRicottone

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