Differences between revisions 3 and 7 (spanning 4 versions)
Revision 3 as of 2022-12-29 20:25:48
Size: 3672
Comment:
Revision 7 as of 2023-03-01 15:30:52
Size: 3379
Comment:
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
## page was renamed from PythonConfigParser
=
ConfigParser =
= Python ConfigParser =
Line 4: 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.
Line 12: Line 17:
== Grammar and Grammar Errors == == Configuration Language ==
Line 18: 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 30: Line 35:
=== Options === === Options and Values ===
Line 32: 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 38: 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 41: 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 48: 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 54: Line 63:
== Parser == === Defaults ===
Line 56: Line 65:
In Python 2, the relevent package was `ConfigParser`. For Python 3 the name was standardized to `configparser`. Default options and values can be in a `DEFAULT` section.
Line 58: Line 67:
{{{
import configparser
c = configparser.ConfigParser()
}}}



=== Interpolation ===

The parser is capable of interpolation. Given this configuration file:

{{{
[Section]
my dir = /Users
some dir = %(my dir)s/me
}}}

The parser can be made to interpret 'some dir' as '/Users/me'.

{{{
c = configparser.ConfigParser(interpolation=configparser.BasicInterpolation())
}}}



=== Getters ===

The primary method of getting a value is the `get()` method. Gotten values are always strings. (The optional fallback argument can specify a value of any type.)

{{{
c.get('Section', 'option')
c.get('Section', 'option', fallback=False)
}}}

Sections of the parser can be accessed using the notation `parser['section']`. This returns a proxy for the internal data structure-if mutated, the parser's data is mutated. This exposes an alternate `get()` method with a positional fallback value.

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

Lastly, there are helper functions for type casting.

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

`getboolean` in particular is useful because it interprets a variety of strings as boolean keywords: `true` and `false`, `yes` and `no`, `on` and `off`, `1` and `0`.

----



== Default Values ==

Defaults are fed into a parser at creation.

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

Defaults can also be set into the default section. The name of this section can be configured in the parser creation (the `default_section` keyword argument) or in the package (as the default value for the `default_section` keyword argument is `configparser.DEFAULTSECT`).
The name of this section can be adjusted by setting the parser's `default_section` argument or by setting the `configparser.DEFAULTSECT` constant.
Line 130: Line 76:
=== Hierarchical Values === === Interpolation ===
Line 132: Line 78:
A common design goal is having default values, then multiple filenames to check for cascading value overwrites.

This design is accomplished by a two-stage import of configuration files.
Configuration can be written with variables by setting the parser's `interpolation` argument, as with `interpolation=configparser.BasicInterpolation()`.
Line 137: Line 81:
with open('defaults.conf', 'r') as f:
    c.read_file(f)
c.read(['/etc/my-app.conf', os.path.expanduser('~/.config/my-app/my-app.conf')])
[Section]
user dir = /Users
my dir = %(my dir)s/me
Line 141: Line 85:

----



== 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)