Size: 3627
Comment:
|
Size: 3149
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. | Until Python 3.11 added `tomllib`, `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 11: | Line 13: |
== Grammar and Grammar Errors == | == Configuration Language == |
Line 17: | Line 19: |
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 29: | Line 31: |
=== Options === | === Options and Values === |
Line 31: | Line 33: |
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 37: | Line 39: |
}}} 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 40: | Line 48: |
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 47: | Line 55: |
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 53: | Line 59: |
== Parser == | === Defaults === |
Line 55: | Line 61: |
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 57: | Line 63: |
{{{ 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 129: | Line 72: |
=== Hierarchical Values === | === Interpolation === |
Line 131: | Line 74: |
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 136: | Line 77: |
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 }}} ---- == Usage == In Python 2, the relevant module was `ConfigParser`. For Python 3 the name was standardized to `configparser`. {{{ 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'}) |
Python ConfigParser
Until Python 3.11 added tomllib, 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.
Contents
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
In Python 2, the relevant module was ConfigParser. For Python 3 the name was standardized to configparser.
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'})