blob: 3b4cb5e6b2407f7b10989444caf64b1bdc8914de [file] [log] [blame]
Guido van Rossum3d209861997-12-09 16:10:31 +00001"""Configuration file parser.
2
Georg Brandl96a60ae2010-07-28 13:13:46 +00003A configuration file consists of sections, lead by a "[section]" header,
Guido van Rossum3d209861997-12-09 16:10:31 +00004and followed by "name: value" entries, with continuations and such in
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00005the style of RFC 822.
Guido van Rossum3d209861997-12-09 16:10:31 +00006
Guido van Rossum3d209861997-12-09 16:10:31 +00007Intrinsic defaults can be specified by passing them into the
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00008ConfigParser constructor as a dictionary.
Guido van Rossum3d209861997-12-09 16:10:31 +00009
10class:
11
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000012ConfigParser -- responsible for parsing a list of
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000013 configuration files, and managing the parsed database.
Guido van Rossum3d209861997-12-09 16:10:31 +000014
15 methods:
16
Fred Drakecc645b92010-09-04 04:35:34 +000017 __init__(defaults=None, dict_type=_default_dict, allow_no_value=False,
Łukasz Langab25a7912010-12-17 01:32:29 +000018 delimiters=('=', ':'), comment_prefixes=('#', ';'),
19 inline_comment_prefixes=None, strict=True,
Łukasz Langadfdd2f72014-09-15 02:08:41 -070020 empty_lines_in_values=True, default_section='DEFAULT',
21 interpolation=<unset>, converters=<unset>):
Georg Brandl96a60ae2010-07-28 13:13:46 +000022 Create the parser. When `defaults' is given, it is initialized into the
23 dictionary or intrinsic defaults. The keys must be strings, the values
Łukasz Langa5c863392010-11-21 13:41:35 +000024 must be appropriate for %()s string interpolation.
Georg Brandl96a60ae2010-07-28 13:13:46 +000025
26 When `dict_type' is given, it will be used to create the dictionary
27 objects for the list of sections, for the options within a section, and
28 for the default values.
29
30 When `delimiters' is given, it will be used as the set of substrings
31 that divide keys from values.
32
33 When `comment_prefixes' is given, it will be used as the set of
Łukasz Langab25a7912010-12-17 01:32:29 +000034 substrings that prefix comments in empty lines. Comments can be
35 indented.
36
37 When `inline_comment_prefixes' is given, it will be used as the set of
38 substrings that prefix comments in non-empty lines.
Georg Brandl96a60ae2010-07-28 13:13:46 +000039
Fred Drakea4923622010-08-09 12:52:45 +000040 When `strict` is True, the parser won't allow for any section or option
41 duplicates while reading from a single source (file, string or
Łukasz Langab25a7912010-12-17 01:32:29 +000042 dictionary). Default is True.
Fred Drakea4923622010-08-09 12:52:45 +000043
Georg Brandl96a60ae2010-07-28 13:13:46 +000044 When `empty_lines_in_values' is False (default: True), each empty line
45 marks the end of an option. Otherwise, internal empty lines of
46 a multiline option are kept as part of the value.
47
48 When `allow_no_value' is True (default: False), options without
49 values are accepted; the value presented for these is None.
Guido van Rossum3d209861997-12-09 16:10:31 +000050
Łukasz Langadfdd2f72014-09-15 02:08:41 -070051 When `default_section' is given, the name of the special section is
52 named accordingly. By default it is called ``"DEFAULT"`` but this can
53 be customized to point to any other valid section name. Its current
54 value can be retrieved using the ``parser_instance.default_section``
55 attribute and may be modified at runtime.
56
57 When `interpolation` is given, it should be an Interpolation subclass
58 instance. It will be used as the handler for option value
Woko45d75fa2019-03-04 10:23:19 +080059 pre-processing when using getters. RawConfigParser objects don't do
Łukasz Langadfdd2f72014-09-15 02:08:41 -070060 any sort of interpolation, whereas ConfigParser uses an instance of
61 BasicInterpolation. The library also provides a ``zc.buildbot``
62 inspired ExtendedInterpolation implementation.
63
64 When `converters` is given, it should be a dictionary where each key
65 represents the name of a type converter and each value is a callable
66 implementing the conversion from string to the desired datatype. Every
67 converter gets its corresponding get*() method on the parser object and
68 section proxies.
69
Barry Warsawf09f6a51999-01-26 22:01:37 +000070 sections()
Georg Brandl96a60ae2010-07-28 13:13:46 +000071 Return all the configuration section names, sans DEFAULT.
Guido van Rossum3d209861997-12-09 16:10:31 +000072
Guido van Rossuma5a24b71999-10-04 19:58:22 +000073 has_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000074 Return whether the given section exists.
Guido van Rossuma5a24b71999-10-04 19:58:22 +000075
Eric S. Raymond649685a2000-07-14 14:28:22 +000076 has_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +000077 Return whether the given option exists in the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +000078
Barry Warsawf09f6a51999-01-26 22:01:37 +000079 options(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000080 Return list of configuration options for the named section.
Guido van Rossum3d209861997-12-09 16:10:31 +000081
Georg Brandl8dcaa732010-07-29 12:17:40 +000082 read(filenames, encoding=None)
Zackery Spytze45473e2018-09-29 10:15:55 -060083 Read and parse the iterable of named configuration files, given by
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000084 name. A single filename is also allowed. Non-existing files
Fred Drake82903142004-05-18 04:24:02 +000085 are ignored. Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000086
Fred Drakea4923622010-08-09 12:52:45 +000087 read_file(f, filename=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000088 Read and parse one configuration file, given as a file object.
Fred Drakea4923622010-08-09 12:52:45 +000089 The filename defaults to f.name; it is only used in error
90 messages (if f has no `name' attribute, the string `<???>' is used).
91
92 read_string(string)
93 Read configuration from a given string.
94
95 read_dict(dictionary)
96 Read configuration from a dictionary. Keys are section names,
97 values are dictionaries with keys and values that should be present
98 in the section. If the used dictionary type preserves order, sections
Fred Drakecc645b92010-09-04 04:35:34 +000099 and their keys will be added in order. Values are automatically
100 converted to strings.
Guido van Rossum3d209861997-12-09 16:10:31 +0000101
Łukasz Langa26d513c2010-11-10 18:57:39 +0000102 get(section, option, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000103 Return a string value for the named option. All % interpolations are
Barry Warsawf09f6a51999-01-26 22:01:37 +0000104 expanded in the return values, based on the defaults passed into the
105 constructor and the DEFAULT section. Additional substitutions may be
106 provided using the `vars' argument, which must be a dictionary whose
Fred Drakecc645b92010-09-04 04:35:34 +0000107 contents override any pre-existing defaults. If `option' is a key in
108 `vars', the value from `vars' is used.
Guido van Rossum3d209861997-12-09 16:10:31 +0000109
Łukasz Langa26d513c2010-11-10 18:57:39 +0000110 getint(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000111 Like get(), but convert value to an integer.
Guido van Rossum3d209861997-12-09 16:10:31 +0000112
Łukasz Langa26d513c2010-11-10 18:57:39 +0000113 getfloat(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000114 Like get(), but convert value to a float.
Guido van Rossum3d209861997-12-09 16:10:31 +0000115
Łukasz Langa26d513c2010-11-10 18:57:39 +0000116 getboolean(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000117 Like get(), but convert value to a boolean (currently case
Neal Norwitzf680cc42002-12-17 01:56:47 +0000118 insensitively defined as 0, false, no, off for False, and 1, true,
119 yes, on for True). Returns False or True.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000120
Łukasz Langa71b37a52010-12-17 21:56:32 +0000121 items(section=_UNSET, raw=False, vars=None)
Łukasz Langa30574692012-12-31 02:18:20 +0100122 If section is given, return a list of tuples with (name, value) for
123 each option in the section. Otherwise, return a list of tuples with
124 (section_name, section_proxy) for each section, including DEFAULTSECT.
Fred Drake2ca041f2002-09-27 15:49:56 +0000125
Eric S. Raymond649685a2000-07-14 14:28:22 +0000126 remove_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000127 Remove the given file section and all its options.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000128
129 remove_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000130 Remove the given option from the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000131
132 set(section, option, value)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000133 Set the given option.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000134
Georg Brandl96a60ae2010-07-28 13:13:46 +0000135 write(fp, space_around_delimiters=True)
136 Write the configuration state in .ini format. If
137 `space_around_delimiters' is True (the default), delimiters
138 between keys and values are surrounded by spaces.
Guido van Rossum3d209861997-12-09 16:10:31 +0000139"""
140
Raymond Hettinger57d1a882011-02-23 00:46:28 +0000141from collections.abc import MutableMapping
John Reese3a5b0d82018-06-05 16:31:33 -0700142from collections import ChainMap as _ChainMap
Łukasz Langa26d513c2010-11-10 18:57:39 +0000143import functools
Fred Drakea4923622010-08-09 12:52:45 +0000144import io
Łukasz Langa26d513c2010-11-10 18:57:39 +0000145import itertools
David Ellis85b8d012017-03-03 17:14:27 +0000146import os
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000147import re
Georg Brandl96a60ae2010-07-28 13:13:46 +0000148import sys
Fred Drakea4923622010-08-09 12:52:45 +0000149import warnings
Guido van Rossum3d209861997-12-09 16:10:31 +0000150
Fred Drakea4923622010-08-09 12:52:45 +0000151__all__ = ["NoSectionError", "DuplicateOptionError", "DuplicateSectionError",
152 "NoOptionError", "InterpolationError", "InterpolationDepthError",
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700153 "InterpolationMissingOptionError", "InterpolationSyntaxError",
154 "ParsingError", "MissingSectionHeaderError",
David Goodger1cbf2062004-10-03 15:55:09 +0000155 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700156 "Interpolation", "BasicInterpolation", "ExtendedInterpolation",
157 "LegacyInterpolation", "SectionProxy", "ConverterMapping",
Fred Drakec2ff9052002-09-27 15:33:11 +0000158 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000159
John Reese3a5b0d82018-06-05 16:31:33 -0700160_default_dict = dict
Guido van Rossum3d209861997-12-09 16:10:31 +0000161DEFAULTSECT = "DEFAULT"
162
Fred Drake2a37f9f2000-09-27 22:43:54 +0000163MAX_INTERPOLATION_DEPTH = 10
164
Guido van Rossum3d209861997-12-09 16:10:31 +0000165
Tim Peters88869f92001-01-14 23:36:06 +0000166
Guido van Rossum3d209861997-12-09 16:10:31 +0000167# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000168class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000169 """Base class for ConfigParser exceptions."""
170
Guido van Rossum3d209861997-12-09 16:10:31 +0000171 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000172 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000173 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000174
Guido van Rossum3d209861997-12-09 16:10:31 +0000175 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000176 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000177
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000178 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000179
Georg Brandl96a60ae2010-07-28 13:13:46 +0000180
Guido van Rossum3d209861997-12-09 16:10:31 +0000181class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000182 """Raised when no section matches a requested option."""
183
Guido van Rossum3d209861997-12-09 16:10:31 +0000184 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000185 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000186 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000187 self.args = (section, )
Guido van Rossum3d209861997-12-09 16:10:31 +0000188
Georg Brandl96a60ae2010-07-28 13:13:46 +0000189
Guido van Rossum3d209861997-12-09 16:10:31 +0000190class DuplicateSectionError(Error):
Fred Drakea4923622010-08-09 12:52:45 +0000191 """Raised when a section is repeated in an input source.
Fred Drake8d5dd982002-12-30 23:51:45 +0000192
Fred Drakea4923622010-08-09 12:52:45 +0000193 Possible repetitions that raise this exception are: multiple creation
194 using the API or in strict parsers when a section is found more than once
195 in a single input file, string or dictionary.
196 """
197
198 def __init__(self, section, source=None, lineno=None):
199 msg = [repr(section), " already exists"]
200 if source is not None:
Łukasz Langaf9b4eb42013-06-23 19:10:25 +0200201 message = ["While reading from ", repr(source)]
Fred Drakea4923622010-08-09 12:52:45 +0000202 if lineno is not None:
203 message.append(" [line {0:2d}]".format(lineno))
204 message.append(": section ")
205 message.extend(msg)
206 msg = message
207 else:
208 msg.insert(0, "Section ")
209 Error.__init__(self, "".join(msg))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000210 self.section = section
Fred Drakea4923622010-08-09 12:52:45 +0000211 self.source = source
212 self.lineno = lineno
213 self.args = (section, source, lineno)
214
215
216class DuplicateOptionError(Error):
217 """Raised by strict parsers when an option is repeated in an input source.
218
219 Current implementation raises this exception only when an option is found
220 more than once in a single file, string or dictionary.
221 """
222
223 def __init__(self, section, option, source=None, lineno=None):
224 msg = [repr(option), " in section ", repr(section),
225 " already exists"]
226 if source is not None:
Łukasz Langaf9b4eb42013-06-23 19:10:25 +0200227 message = ["While reading from ", repr(source)]
Fred Drakea4923622010-08-09 12:52:45 +0000228 if lineno is not None:
229 message.append(" [line {0:2d}]".format(lineno))
230 message.append(": option ")
231 message.extend(msg)
232 msg = message
233 else:
234 msg.insert(0, "Option ")
235 Error.__init__(self, "".join(msg))
236 self.section = section
237 self.option = option
238 self.source = source
239 self.lineno = lineno
240 self.args = (section, option, source, lineno)
Guido van Rossum3d209861997-12-09 16:10:31 +0000241
Georg Brandl96a60ae2010-07-28 13:13:46 +0000242
Guido van Rossum3d209861997-12-09 16:10:31 +0000243class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000244 """A requested option was not found."""
245
Guido van Rossum3d209861997-12-09 16:10:31 +0000246 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000247 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000248 (option, section))
249 self.option = option
250 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000251 self.args = (option, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000252
Georg Brandl96a60ae2010-07-28 13:13:46 +0000253
Guido van Rossum3d209861997-12-09 16:10:31 +0000254class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000255 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000256
Fred Drakee2c64912002-12-31 17:23:27 +0000257 def __init__(self, option, section, msg):
258 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000259 self.option = option
260 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000261 self.args = (option, section, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000262
Georg Brandl96a60ae2010-07-28 13:13:46 +0000263
Fred Drakee2c64912002-12-31 17:23:27 +0000264class InterpolationMissingOptionError(InterpolationError):
265 """A string substitution required a setting which was not available."""
266
267 def __init__(self, option, section, rawval, reference):
Robert Collinsac37ba02015-08-14 11:11:35 +1200268 msg = ("Bad value substitution: option {!r} in section {!r} contains "
269 "an interpolation key {!r} which is not a valid option name. "
270 "Raw value: {!r}".format(option, section, reference, rawval))
Fred Drakee2c64912002-12-31 17:23:27 +0000271 InterpolationError.__init__(self, option, section, msg)
272 self.reference = reference
Michael Foordbd6c0792010-07-25 23:09:25 +0000273 self.args = (option, section, rawval, reference)
Fred Drakee2c64912002-12-31 17:23:27 +0000274
Georg Brandl96a60ae2010-07-28 13:13:46 +0000275
Fred Drakee2c64912002-12-31 17:23:27 +0000276class InterpolationSyntaxError(InterpolationError):
Fred Drakea4923622010-08-09 12:52:45 +0000277 """Raised when the source text contains invalid syntax.
278
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000279 Current implementation raises this exception when the source text into
280 which substitutions are made does not conform to the required syntax.
Fred Drakea4923622010-08-09 12:52:45 +0000281 """
Neal Norwitzce1d9442002-12-30 23:38:47 +0000282
Georg Brandl96a60ae2010-07-28 13:13:46 +0000283
Fred Drakee2c64912002-12-31 17:23:27 +0000284class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000285 """Raised when substitutions are nested too deeply."""
286
Fred Drake2a37f9f2000-09-27 22:43:54 +0000287 def __init__(self, option, section, rawval):
Robert Collinsac37ba02015-08-14 11:11:35 +1200288 msg = ("Recursion limit exceeded in value substitution: option {!r} "
289 "in section {!r} contains an interpolation key which "
290 "cannot be substituted in {} steps. Raw value: {!r}"
291 "".format(option, section, MAX_INTERPOLATION_DEPTH,
292 rawval))
Fred Drakee2c64912002-12-31 17:23:27 +0000293 InterpolationError.__init__(self, option, section, msg)
Michael Foordbd6c0792010-07-25 23:09:25 +0000294 self.args = (option, section, rawval)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000295
Georg Brandl96a60ae2010-07-28 13:13:46 +0000296
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000297class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000298 """Raised when a configuration file does not follow legal syntax."""
299
Fred Drakea4923622010-08-09 12:52:45 +0000300 def __init__(self, source=None, filename=None):
301 # Exactly one of `source'/`filename' arguments has to be given.
302 # `filename' kept for compatibility.
303 if filename and source:
304 raise ValueError("Cannot specify both `filename' and `source'. "
305 "Use `source'.")
306 elif not filename and not source:
307 raise ValueError("Required argument `source' not given.")
308 elif filename:
309 source = filename
Serhiy Storchakabc27a052014-02-06 22:49:45 +0200310 Error.__init__(self, 'Source contains parsing errors: %r' % source)
Fred Drakea4923622010-08-09 12:52:45 +0000311 self.source = source
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000312 self.errors = []
Fred Drakea4923622010-08-09 12:52:45 +0000313 self.args = (source, )
314
315 @property
316 def filename(self):
317 """Deprecated, use `source'."""
318 warnings.warn(
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000319 "The 'filename' attribute will be removed in future versions. "
Fred Drakea4923622010-08-09 12:52:45 +0000320 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000321 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000322 )
323 return self.source
324
325 @filename.setter
326 def filename(self, value):
327 """Deprecated, user `source'."""
328 warnings.warn(
329 "The 'filename' attribute will be removed in future versions. "
330 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000331 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000332 )
333 self.source = value
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000334
335 def append(self, lineno, line):
336 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000337 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000338
Georg Brandl96a60ae2010-07-28 13:13:46 +0000339
Fred Drake2a37f9f2000-09-27 22:43:54 +0000340class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000341 """Raised when a key-value pair is found before any section header."""
342
Fred Drake2a37f9f2000-09-27 22:43:54 +0000343 def __init__(self, filename, lineno, line):
344 Error.__init__(
345 self,
Serhiy Storchakabc27a052014-02-06 22:49:45 +0200346 'File contains no section headers.\nfile: %r, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000347 (filename, lineno, line))
Fred Drakea4923622010-08-09 12:52:45 +0000348 self.source = filename
Fred Drake2a37f9f2000-09-27 22:43:54 +0000349 self.lineno = lineno
350 self.line = line
Michael Foordbd6c0792010-07-25 23:09:25 +0000351 self.args = (filename, lineno, line)
Guido van Rossum3d209861997-12-09 16:10:31 +0000352
Georg Brandl96a60ae2010-07-28 13:13:46 +0000353
Fred Drakecc645b92010-09-04 04:35:34 +0000354# Used in parser getters to indicate the default behaviour when a specific
355# option is not found it to raise an exception. Created to enable `None' as
356# a valid fallback value.
357_UNSET = object()
358
359
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000360class Interpolation:
361 """Dummy interpolation that passes the value through with no changes."""
362
363 def before_get(self, parser, section, option, value, defaults):
364 return value
365
366 def before_set(self, parser, section, option, value):
367 return value
368
369 def before_read(self, parser, section, option, value):
370 return value
371
372 def before_write(self, parser, section, option, value):
373 return value
374
375
376class BasicInterpolation(Interpolation):
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000377 """Interpolation as implemented in the classic ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000378
379 The option values can contain format strings which refer to other values in
380 the same section, or values in the special default section.
381
382 For example:
383
384 something: %(dir)s/whatever
385
386 would resolve the "%(dir)s" to the value of dir. All reference
387 expansions are done late, on demand. If a user needs to use a bare % in
Ezio Melottie130a522011-10-19 10:58:56 +0300388 a configuration file, she can escape it by writing %%. Other % usage
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000389 is considered a user error and raises `InterpolationSyntaxError'."""
390
391 _KEYCRE = re.compile(r"%\(([^)]+)\)s")
392
393 def before_get(self, parser, section, option, value, defaults):
394 L = []
395 self._interpolate_some(parser, option, L, value, section, defaults, 1)
396 return ''.join(L)
397
398 def before_set(self, parser, section, option, value):
399 tmp_value = value.replace('%%', '') # escaped percent signs
400 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
401 if '%' in tmp_value:
402 raise ValueError("invalid interpolation syntax in %r at "
403 "position %d" % (value, tmp_value.find('%')))
404 return value
405
406 def _interpolate_some(self, parser, option, accum, rest, section, map,
407 depth):
Robert Collinsac37ba02015-08-14 11:11:35 +1200408 rawval = parser.get(section, option, raw=True, fallback=rest)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000409 if depth > MAX_INTERPOLATION_DEPTH:
Robert Collinsac37ba02015-08-14 11:11:35 +1200410 raise InterpolationDepthError(option, section, rawval)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000411 while rest:
412 p = rest.find("%")
413 if p < 0:
414 accum.append(rest)
415 return
416 if p > 0:
417 accum.append(rest[:p])
418 rest = rest[p:]
419 # p is no longer used
420 c = rest[1:2]
421 if c == "%":
422 accum.append("%")
423 rest = rest[2:]
424 elif c == "(":
425 m = self._KEYCRE.match(rest)
426 if m is None:
427 raise InterpolationSyntaxError(option, section,
428 "bad interpolation variable reference %r" % rest)
429 var = parser.optionxform(m.group(1))
430 rest = rest[m.end():]
431 try:
432 v = map[var]
433 except KeyError:
434 raise InterpolationMissingOptionError(
Robert Collinsf7a92672015-08-14 11:47:41 +1200435 option, section, rawval, var) from None
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000436 if "%" in v:
437 self._interpolate_some(parser, option, accum, v,
438 section, map, depth + 1)
439 else:
440 accum.append(v)
441 else:
442 raise InterpolationSyntaxError(
443 option, section,
444 "'%%' must be followed by '%%' or '(', "
445 "found: %r" % (rest,))
446
447
448class ExtendedInterpolation(Interpolation):
449 """Advanced variant of interpolation, supports the syntax used by
450 `zc.buildout'. Enables interpolation between sections."""
451
452 _KEYCRE = re.compile(r"\$\{([^}]+)\}")
453
454 def before_get(self, parser, section, option, value, defaults):
455 L = []
456 self._interpolate_some(parser, option, L, value, section, defaults, 1)
457 return ''.join(L)
458
459 def before_set(self, parser, section, option, value):
460 tmp_value = value.replace('$$', '') # escaped dollar signs
461 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
462 if '$' in tmp_value:
463 raise ValueError("invalid interpolation syntax in %r at "
Łukasz Langafa608182013-04-24 01:25:18 +0200464 "position %d" % (value, tmp_value.find('$')))
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000465 return value
466
467 def _interpolate_some(self, parser, option, accum, rest, section, map,
468 depth):
Robert Collinsac37ba02015-08-14 11:11:35 +1200469 rawval = parser.get(section, option, raw=True, fallback=rest)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000470 if depth > MAX_INTERPOLATION_DEPTH:
Robert Collinsac37ba02015-08-14 11:11:35 +1200471 raise InterpolationDepthError(option, section, rawval)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000472 while rest:
473 p = rest.find("$")
474 if p < 0:
475 accum.append(rest)
476 return
477 if p > 0:
478 accum.append(rest[:p])
479 rest = rest[p:]
480 # p is no longer used
481 c = rest[1:2]
482 if c == "$":
483 accum.append("$")
484 rest = rest[2:]
485 elif c == "{":
486 m = self._KEYCRE.match(rest)
487 if m is None:
488 raise InterpolationSyntaxError(option, section,
489 "bad interpolation variable reference %r" % rest)
Łukasz Langae698cd52011-04-28 10:58:57 +0200490 path = m.group(1).split(':')
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000491 rest = rest[m.end():]
492 sect = section
493 opt = option
494 try:
495 if len(path) == 1:
Łukasz Langae698cd52011-04-28 10:58:57 +0200496 opt = parser.optionxform(path[0])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000497 v = map[opt]
498 elif len(path) == 2:
499 sect = path[0]
Łukasz Langae698cd52011-04-28 10:58:57 +0200500 opt = parser.optionxform(path[1])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000501 v = parser.get(sect, opt, raw=True)
502 else:
503 raise InterpolationSyntaxError(
504 option, section,
505 "More than one ':' found: %r" % (rest,))
Łukasz Langa71b37a52010-12-17 21:56:32 +0000506 except (KeyError, NoSectionError, NoOptionError):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000507 raise InterpolationMissingOptionError(
Robert Collinsf7a92672015-08-14 11:47:41 +1200508 option, section, rawval, ":".join(path)) from None
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000509 if "$" in v:
510 self._interpolate_some(parser, opt, accum, v, sect,
511 dict(parser.items(sect, raw=True)),
512 depth + 1)
513 else:
514 accum.append(v)
515 else:
516 raise InterpolationSyntaxError(
517 option, section,
518 "'$' must be followed by '$' or '{', "
519 "found: %r" % (rest,))
520
521
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000522class LegacyInterpolation(Interpolation):
523 """Deprecated interpolation used in old versions of ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000524 Use BasicInterpolation or ExtendedInterpolation instead."""
525
526 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
527
528 def before_get(self, parser, section, option, value, vars):
529 rawval = value
530 depth = MAX_INTERPOLATION_DEPTH
531 while depth: # Loop through this until it's done
532 depth -= 1
533 if value and "%(" in value:
534 replace = functools.partial(self._interpolation_replace,
535 parser=parser)
536 value = self._KEYCRE.sub(replace, value)
537 try:
538 value = value % vars
539 except KeyError as e:
540 raise InterpolationMissingOptionError(
Łukasz Langa949053b2014-09-04 01:36:33 -0700541 option, section, rawval, e.args[0]) from None
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000542 else:
543 break
544 if value and "%(" in value:
545 raise InterpolationDepthError(option, section, rawval)
546 return value
547
548 def before_set(self, parser, section, option, value):
549 return value
550
551 @staticmethod
552 def _interpolation_replace(match, parser):
553 s = match.group(1)
554 if s is None:
555 return match.group()
556 else:
557 return "%%(%s)s" % parser.optionxform(s)
558
559
Łukasz Langa26d513c2010-11-10 18:57:39 +0000560class RawConfigParser(MutableMapping):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000561 """ConfigParser that does not do interpolation."""
562
563 # Regular expressions for parsing section headers and options
564 _SECT_TMPL = r"""
565 \[ # [
566 (?P<header>[^]]+) # very permissive!
567 \] # ]
568 """
569 _OPT_TMPL = r"""
570 (?P<option>.*?) # very permissive!
571 \s*(?P<vi>{delim})\s* # any number of space/tab,
572 # followed by any of the
573 # allowed delimiters,
574 # followed by any space/tab
575 (?P<value>.*)$ # everything up to eol
576 """
577 _OPT_NV_TMPL = r"""
578 (?P<option>.*?) # very permissive!
579 \s*(?: # any number of space/tab,
580 (?P<vi>{delim})\s* # optionally followed by
581 # any of the allowed
582 # delimiters, followed by any
583 # space/tab
584 (?P<value>.*))?$ # everything up to eol
585 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000586 # Interpolation algorithm to be used if the user does not specify another
587 _DEFAULT_INTERPOLATION = Interpolation()
Georg Brandl96a60ae2010-07-28 13:13:46 +0000588 # Compiled regular expression for matching sections
589 SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
590 # Compiled regular expression for matching options with typical separators
591 OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
592 # Compiled regular expression for matching options with optional values
593 # delimited using typical separators
594 OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
595 # Compiled regular expression for matching leading whitespace in a line
596 NONSPACECRE = re.compile(r"\S")
Fred Drakecc645b92010-09-04 04:35:34 +0000597 # Possible boolean values in the configuration.
598 BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
599 '0': False, 'no': False, 'false': False, 'off': False}
Georg Brandl96a60ae2010-07-28 13:13:46 +0000600
Fred Drake03c44a32010-02-19 06:08:41 +0000601 def __init__(self, defaults=None, dict_type=_default_dict,
Fred Drakea4923622010-08-09 12:52:45 +0000602 allow_no_value=False, *, delimiters=('=', ':'),
Łukasz Langab25a7912010-12-17 01:32:29 +0000603 comment_prefixes=('#', ';'), inline_comment_prefixes=None,
604 strict=True, empty_lines_in_values=True,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000605 default_section=DEFAULTSECT,
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700606 interpolation=_UNSET, converters=_UNSET):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000607
Thomas Wouters89f507f2006-12-13 04:49:30 +0000608 self._dict = dict_type
609 self._sections = self._dict()
610 self._defaults = self._dict()
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700611 self._converters = ConverterMapping(self)
Łukasz Langa49afa382010-11-11 19:53:23 +0000612 self._proxies = self._dict()
Łukasz Langac264c092010-11-20 16:15:37 +0000613 self._proxies[default_section] = SectionProxy(self, default_section)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000614 self._delimiters = tuple(delimiters)
615 if delimiters == ('=', ':'):
616 self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
617 else:
Fred Drakea4923622010-08-09 12:52:45 +0000618 d = "|".join(re.escape(d) for d in delimiters)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000619 if allow_no_value:
Fred Drakea4923622010-08-09 12:52:45 +0000620 self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000621 re.VERBOSE)
622 else:
Fred Drakea4923622010-08-09 12:52:45 +0000623 self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000624 re.VERBOSE)
Łukasz Langab25a7912010-12-17 01:32:29 +0000625 self._comment_prefixes = tuple(comment_prefixes or ())
626 self._inline_comment_prefixes = tuple(inline_comment_prefixes or ())
Fred Drakea4923622010-08-09 12:52:45 +0000627 self._strict = strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000628 self._allow_no_value = allow_no_value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000629 self._empty_lines_in_values = empty_lines_in_values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000630 self.default_section=default_section
Łukasz Langa1aa422f2011-04-28 17:03:45 +0200631 self._interpolation = interpolation
632 if self._interpolation is _UNSET:
633 self._interpolation = self._DEFAULT_INTERPOLATION
634 if self._interpolation is None:
635 self._interpolation = Interpolation()
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700636 if converters is not _UNSET:
637 self._converters.update(converters)
James Tocknell44e6ad82017-08-22 08:46:30 +1000638 if defaults:
Łukasz Langaa5fab172017-08-24 09:43:53 -0700639 self._read_defaults(defaults)
Guido van Rossum3d209861997-12-09 16:10:31 +0000640
641 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000642 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000643
644 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000645 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000646 # self._sections will never have [DEFAULT] in it
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000647 return list(self._sections.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000648
649 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000650 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000651
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000652 Raise DuplicateSectionError if a section by the specified name
Łukasz Langac264c092010-11-20 16:15:37 +0000653 already exists. Raise ValueError if name is DEFAULT.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000654 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000655 if section == self.default_section:
Łukasz Langa3a11e712010-12-03 22:15:19 +0000656 raise ValueError('Invalid section name: %r' % section)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000657
Fred Drakefce65572002-10-25 18:08:18 +0000658 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000659 raise DuplicateSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000660 self._sections[section] = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000661 self._proxies[section] = SectionProxy(self, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000662
663 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000664 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000665
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000666 The DEFAULT section is not acknowledged.
667 """
Fred Drakefce65572002-10-25 18:08:18 +0000668 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000669
670 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000671 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000672 try:
Fred Drakefce65572002-10-25 18:08:18 +0000673 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000674 except KeyError:
Łukasz Langa949053b2014-09-04 01:36:33 -0700675 raise NoSectionError(section) from None
Fred Drakefce65572002-10-25 18:08:18 +0000676 opts.update(self._defaults)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000677 return list(opts.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000678
Georg Brandl8dcaa732010-07-29 12:17:40 +0000679 def read(self, filenames, encoding=None):
Zackery Spytze45473e2018-09-29 10:15:55 -0600680 """Read and parse a filename or an iterable of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000681
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000682 Files that cannot be opened are silently ignored; this is
Zackery Spytze45473e2018-09-29 10:15:55 -0600683 designed so that you can specify an iterable of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000684 configuration file locations (e.g. current directory, user's
685 home directory, systemwide directory), and all existing
Zackery Spytze45473e2018-09-29 10:15:55 -0600686 configuration files in the iterable will be read. A single
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000687 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000688
689 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000690 """
Vincent Michele3148532017-11-02 13:47:04 +0100691 if isinstance(filenames, (str, bytes, os.PathLike)):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000692 filenames = [filenames]
Inada Naoki48274832021-03-29 12:28:14 +0900693 encoding = io.text_encoding(encoding)
Fred Drake82903142004-05-18 04:24:02 +0000694 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000695 for filename in filenames:
696 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000697 with open(filename, encoding=encoding) as fp:
698 self._read(fp, filename)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200699 except OSError:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000700 continue
David Ellis85b8d012017-03-03 17:14:27 +0000701 if isinstance(filename, os.PathLike):
702 filename = os.fspath(filename)
Fred Drake82903142004-05-18 04:24:02 +0000703 read_ok.append(filename)
704 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000705
Fred Drakea4923622010-08-09 12:52:45 +0000706 def read_file(self, f, source=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000707 """Like read() but the argument must be a file-like object.
708
Łukasz Langadaab1c82011-04-27 18:10:05 +0200709 The `f' argument must be iterable, returning one line at a time.
710 Optional second argument is the `source' specifying the name of the
711 file being read. If not given, it is taken from f.name. If `f' has no
712 `name' attribute, `<???>' is used.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000713 """
Fred Drakea4923622010-08-09 12:52:45 +0000714 if source is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000715 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000716 source = f.name
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000717 except AttributeError:
Fred Drakea4923622010-08-09 12:52:45 +0000718 source = '<???>'
719 self._read(f, source)
720
721 def read_string(self, string, source='<string>'):
722 """Read configuration from a given string."""
723 sfile = io.StringIO(string)
724 self.read_file(sfile, source)
725
726 def read_dict(self, dictionary, source='<dict>'):
727 """Read configuration from a dictionary.
728
729 Keys are section names, values are dictionaries with keys and values
730 that should be present in the section. If the used dictionary type
731 preserves order, sections and their keys will be added in order.
732
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000733 All types held in the dictionary are converted to strings during
734 reading, including section names, option names and keys.
735
Fred Drakea4923622010-08-09 12:52:45 +0000736 Optional second argument is the `source' specifying the name of the
737 dictionary being read.
738 """
739 elements_added = set()
740 for section, keys in dictionary.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000741 section = str(section)
Fred Drakea4923622010-08-09 12:52:45 +0000742 try:
743 self.add_section(section)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000744 except (DuplicateSectionError, ValueError):
Fred Drakea4923622010-08-09 12:52:45 +0000745 if self._strict and section in elements_added:
746 raise
Łukasz Langa71b37a52010-12-17 21:56:32 +0000747 elements_added.add(section)
Fred Drakea4923622010-08-09 12:52:45 +0000748 for key, value in keys.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000749 key = self.optionxform(str(key))
Fred Drakecc645b92010-09-04 04:35:34 +0000750 if value is not None:
751 value = str(value)
Fred Drakea4923622010-08-09 12:52:45 +0000752 if self._strict and (section, key) in elements_added:
753 raise DuplicateOptionError(section, key, source)
754 elements_added.add((section, key))
755 self.set(section, key, value)
756
757 def readfp(self, fp, filename=None):
758 """Deprecated, use read_file instead."""
759 warnings.warn(
760 "This method will be removed in future versions. "
761 "Use 'parser.read_file()' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000762 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000763 )
764 self.read_file(fp, source=filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000765
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000766 def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000767 """Get an option value for a given section.
768
769 If `vars' is provided, it must be a dictionary. The option is looked up
770 in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000771 If the key is not found and `fallback' is provided, it is used as
772 a fallback value. `None' can be provided as a `fallback' value.
773
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000774 If interpolation is enabled and the optional argument `raw' is False,
775 all interpolations are expanded in the return values.
776
777 Arguments `raw', `vars', and `fallback' are keyword only.
778
779 The section DEFAULT is special.
Fred Drakecc645b92010-09-04 04:35:34 +0000780 """
781 try:
782 d = self._unify_values(section, vars)
783 except NoSectionError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000784 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000785 raise
Fred Drakefce65572002-10-25 18:08:18 +0000786 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000787 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000788 option = self.optionxform(option)
789 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000790 value = d[option]
Fred Drakecc645b92010-09-04 04:35:34 +0000791 except KeyError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000792 if fallback is _UNSET:
Fred Drakefce65572002-10-25 18:08:18 +0000793 raise NoOptionError(option, section)
Fred Drakecc645b92010-09-04 04:35:34 +0000794 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000795 return fallback
Fred Drake2a37f9f2000-09-27 22:43:54 +0000796
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000797 if raw or value is None:
798 return value
799 else:
800 return self._interpolation.before_get(self, section, option, value,
801 d)
Fred Drake2ca041f2002-09-27 15:49:56 +0000802
Łukasz Langa26d513c2010-11-10 18:57:39 +0000803 def _get(self, section, conv, option, **kwargs):
804 return conv(self.get(section, option, **kwargs))
Guido van Rossum3d209861997-12-09 16:10:31 +0000805
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700806 def _get_conv(self, section, option, conv, *, raw=False, vars=None,
807 fallback=_UNSET, **kwargs):
Fred Drakecc645b92010-09-04 04:35:34 +0000808 try:
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700809 return self._get(section, conv, option, raw=raw, vars=vars,
810 **kwargs)
Fred Drakecc645b92010-09-04 04:35:34 +0000811 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000812 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000813 raise
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700814 return fallback
815
816 # getint, getfloat and getboolean provided directly for backwards compat
817 def getint(self, section, option, *, raw=False, vars=None,
818 fallback=_UNSET, **kwargs):
819 return self._get_conv(section, option, int, raw=raw, vars=vars,
820 fallback=fallback, **kwargs)
Guido van Rossum3d209861997-12-09 16:10:31 +0000821
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000822 def getfloat(self, section, option, *, raw=False, vars=None,
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700823 fallback=_UNSET, **kwargs):
824 return self._get_conv(section, option, float, raw=raw, vars=vars,
825 fallback=fallback, **kwargs)
Guido van Rossum3d209861997-12-09 16:10:31 +0000826
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000827 def getboolean(self, section, option, *, raw=False, vars=None,
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700828 fallback=_UNSET, **kwargs):
829 return self._get_conv(section, option, self._convert_to_boolean,
830 raw=raw, vars=vars, fallback=fallback, **kwargs)
Guido van Rossum3d209861997-12-09 16:10:31 +0000831
Łukasz Langa71b37a52010-12-17 21:56:32 +0000832 def items(self, section=_UNSET, raw=False, vars=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000833 """Return a list of (name, value) tuples for each option in a section.
834
835 All % interpolations are expanded in the return values, based on the
836 defaults passed into the constructor, unless the optional argument
837 `raw' is true. Additional substitutions may be provided using the
838 `vars' argument, which must be a dictionary whose contents overrides
839 any pre-existing defaults.
840
841 The section DEFAULT is special.
842 """
Łukasz Langa71b37a52010-12-17 21:56:32 +0000843 if section is _UNSET:
844 return super().items()
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000845 d = self._defaults.copy()
846 try:
847 d.update(self._sections[section])
848 except KeyError:
849 if section != self.default_section:
850 raise NoSectionError(section)
Chris Bradbury1d4a7332018-04-23 20:16:17 +0100851 orig_keys = list(d.keys())
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000852 # Update with the entry specific variables
853 if vars:
854 for key, value in vars.items():
855 d[self.optionxform(key)] = value
Łukasz Langa24bcc612010-12-04 11:48:11 +0000856 value_getter = lambda option: self._interpolation.before_get(self,
857 section, option, d[option], d)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000858 if raw:
Łukasz Langa24bcc612010-12-04 11:48:11 +0000859 value_getter = lambda option: d[option]
Chris Bradbury1d4a7332018-04-23 20:16:17 +0100860 return [(option, value_getter(option)) for option in orig_keys]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000861
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100862 def popitem(self):
863 """Remove a section from the parser and return it as
864 a (section_name, section_proxy) tuple. If no section is present, raise
865 KeyError.
866
867 The section DEFAULT is never returned because it cannot be removed.
868 """
869 for key in self.sections():
870 value = self[key]
871 del self[key]
872 return key, value
873 raise KeyError
874
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000875 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000876 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000877
Eric S. Raymond417c4892000-07-10 18:11:00 +0000878 def has_option(self, section, option):
Łukasz Langa71b37a52010-12-17 21:56:32 +0000879 """Check for the existence of a given option in a given section.
880 If the specified `section' is None or an empty string, DEFAULT is
881 assumed. If the specified `section' does not exist, returns False."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000882 if not section or section == self.default_section:
Fred Drakec2ff9052002-09-27 15:33:11 +0000883 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000884 return option in self._defaults
885 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000886 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000887 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000888 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000889 return (option in self._sections[section]
890 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000891
Fred Drake03c44a32010-02-19 06:08:41 +0000892 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000893 """Set an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000894 if value:
895 value = self._interpolation.before_set(self, section, option,
896 value)
897 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000898 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000899 else:
900 try:
Fred Drakefce65572002-10-25 18:08:18 +0000901 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000902 except KeyError:
Łukasz Langa949053b2014-09-04 01:36:33 -0700903 raise NoSectionError(section) from None
Fred Drakec2ff9052002-09-27 15:33:11 +0000904 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000905
Georg Brandl96a60ae2010-07-28 13:13:46 +0000906 def write(self, fp, space_around_delimiters=True):
907 """Write an .ini-format representation of the configuration state.
908
909 If `space_around_delimiters' is True (the default), delimiters
910 between keys and values are surrounded by spaces.
911 """
912 if space_around_delimiters:
913 d = " {} ".format(self._delimiters[0])
914 else:
915 d = self._delimiters[0]
Fred Drakefce65572002-10-25 18:08:18 +0000916 if self._defaults:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000917 self._write_section(fp, self.default_section,
Łukasz Langac264c092010-11-20 16:15:37 +0000918 self._defaults.items(), d)
Fred Drakefce65572002-10-25 18:08:18 +0000919 for section in self._sections:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000920 self._write_section(fp, section,
921 self._sections[section].items(), d)
922
923 def _write_section(self, fp, section_name, section_items, delimiter):
924 """Write a single section to the specified `fp'."""
925 fp.write("[{}]\n".format(section_name))
926 for key, value in section_items:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000927 value = self._interpolation.before_write(self, section_name, key,
928 value)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000929 if value is not None or not self._allow_no_value:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000930 value = delimiter + str(value).replace('\n', '\n\t')
931 else:
932 value = ""
933 fp.write("{}{}\n".format(key, value))
934 fp.write("\n")
Eric S. Raymond417c4892000-07-10 18:11:00 +0000935
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000936 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000937 """Remove an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000938 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000939 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000940 else:
941 try:
Fred Drakefce65572002-10-25 18:08:18 +0000942 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000943 except KeyError:
Łukasz Langa949053b2014-09-04 01:36:33 -0700944 raise NoSectionError(section) from None
Fred Drake3c823aa2001-02-26 21:55:34 +0000945 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000946 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000947 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000948 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000949 return existed
950
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000951 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000952 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000953 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000954 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000955 del self._sections[section]
Łukasz Langa49afa382010-11-11 19:53:23 +0000956 del self._proxies[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000957 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000958
Łukasz Langa26d513c2010-11-10 18:57:39 +0000959 def __getitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000960 if key != self.default_section and not self.has_section(key):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000961 raise KeyError(key)
Łukasz Langa49afa382010-11-11 19:53:23 +0000962 return self._proxies[key]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000963
964 def __setitem__(self, key, value):
965 # To conform with the mapping protocol, overwrites existing values in
966 # the section.
Cheryl Sabella33cd0582018-06-12 16:37:51 -0400967 if key in self and self[key] is value:
968 return
Łukasz Langa26d513c2010-11-10 18:57:39 +0000969 # XXX this is not atomic if read_dict fails at any point. Then again,
970 # no update method in configparser is atomic in this implementation.
Łukasz Langa02101942012-12-31 13:55:11 +0100971 if key == self.default_section:
972 self._defaults.clear()
Łukasz Langaa821f822013-01-01 22:33:19 +0100973 elif key in self._sections:
974 self._sections[key].clear()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000975 self.read_dict({key: value})
976
977 def __delitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000978 if key == self.default_section:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000979 raise ValueError("Cannot remove the default section.")
980 if not self.has_section(key):
981 raise KeyError(key)
982 self.remove_section(key)
983
984 def __contains__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000985 return key == self.default_section or self.has_section(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000986
987 def __len__(self):
988 return len(self._sections) + 1 # the default section
989
990 def __iter__(self):
991 # XXX does it break when underlying container state changed?
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000992 return itertools.chain((self.default_section,), self._sections.keys())
Łukasz Langa26d513c2010-11-10 18:57:39 +0000993
Fred Drakefce65572002-10-25 18:08:18 +0000994 def _read(self, fp, fpname):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000995 """Parse a sectioned configuration file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000996
Fred Drakea4923622010-08-09 12:52:45 +0000997 Each section in a configuration file contains a header, indicated by
998 a name in square brackets (`[]'), plus key/value options, indicated by
Georg Brandl96a60ae2010-07-28 13:13:46 +0000999 `name' and `value' delimited with a specific substring (`=' or `:' by
1000 default).
1001
Fred Drakea4923622010-08-09 12:52:45 +00001002 Values can span multiple lines, as long as they are indented deeper
1003 than the first line of the value. Depending on the parser's mode, blank
1004 lines may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +00001005
1006 Configuration files may include comments, prefixed by specific
Fred Drakea4923622010-08-09 12:52:45 +00001007 characters (`#' and `;' by default). Comments may appear on their own
1008 in an otherwise empty line or may be entered in lines holding values or
Georg Brandl96a60ae2010-07-28 13:13:46 +00001009 section names.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001010 """
Fred Drakea4923622010-08-09 12:52:45 +00001011 elements_added = set()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001012 cursect = None # None, or a dictionary
Fred Drakea4923622010-08-09 12:52:45 +00001013 sectname = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001014 optname = None
1015 lineno = 0
Georg Brandl96a60ae2010-07-28 13:13:46 +00001016 indent_level = 0
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001017 e = None # None, or an exception
Georg Brandl96a60ae2010-07-28 13:13:46 +00001018 for lineno, line in enumerate(fp, start=1):
Łukasz Langacba24322012-07-07 18:54:08 +02001019 comment_start = sys.maxsize
Georg Brandl96a60ae2010-07-28 13:13:46 +00001020 # strip inline comments
Łukasz Langacba24322012-07-07 18:54:08 +02001021 inline_prefixes = {p: -1 for p in self._inline_comment_prefixes}
1022 while comment_start == sys.maxsize and inline_prefixes:
1023 next_prefixes = {}
1024 for prefix, index in inline_prefixes.items():
1025 index = line.find(prefix, index+1)
1026 if index == -1:
1027 continue
1028 next_prefixes[prefix] = index
1029 if index == 0 or (index > 0 and line[index-1].isspace()):
1030 comment_start = min(comment_start, index)
1031 inline_prefixes = next_prefixes
Łukasz Langab25a7912010-12-17 01:32:29 +00001032 # strip full line comments
1033 for prefix in self._comment_prefixes:
1034 if line.strip().startswith(prefix):
1035 comment_start = 0
1036 break
Łukasz Langacba24322012-07-07 18:54:08 +02001037 if comment_start == sys.maxsize:
1038 comment_start = None
Georg Brandl96a60ae2010-07-28 13:13:46 +00001039 value = line[:comment_start].strip()
1040 if not value:
Georg Brandlf206d0e2010-07-29 11:56:20 +00001041 if self._empty_lines_in_values:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001042 # add empty line to the value, but only if there was no
1043 # comment on the line
Georg Brandlf206d0e2010-07-29 11:56:20 +00001044 if (comment_start is None and
1045 cursect is not None and
1046 optname and
1047 cursect[optname] is not None):
1048 cursect[optname].append('') # newlines added at join
Georg Brandl96a60ae2010-07-28 13:13:46 +00001049 else:
1050 # empty line marks end of value
1051 indent_level = sys.maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001052 continue
1053 # continuation line?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001054 first_nonspace = self.NONSPACECRE.search(line)
1055 cur_indent_level = first_nonspace.start() if first_nonspace else 0
1056 if (cursect is not None and optname and
1057 cur_indent_level > indent_level):
1058 cursect[optname].append(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001059 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001060 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001061 indent_level = cur_indent_level
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001062 # is it a section header?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001063 mo = self.SECTCRE.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001064 if mo:
1065 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +00001066 if sectname in self._sections:
Fred Drakea4923622010-08-09 12:52:45 +00001067 if self._strict and sectname in elements_added:
1068 raise DuplicateSectionError(sectname, fpname,
1069 lineno)
Fred Drakefce65572002-10-25 18:08:18 +00001070 cursect = self._sections[sectname]
Fred Drakea4923622010-08-09 12:52:45 +00001071 elements_added.add(sectname)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001072 elif sectname == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001073 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001074 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001075 cursect = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +00001076 self._sections[sectname] = cursect
Łukasz Langa49afa382010-11-11 19:53:23 +00001077 self._proxies[sectname] = SectionProxy(self, sectname)
Fred Drakea4923622010-08-09 12:52:45 +00001078 elements_added.add(sectname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001079 # So sections can't start with a continuation line
1080 optname = None
1081 # no section header in the file?
1082 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001083 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001084 # an option line?
1085 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001086 mo = self._optcre.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001087 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +00001088 optname, vi, optval = mo.group('option', 'vi', 'value')
Georg Brandl96a60ae2010-07-28 13:13:46 +00001089 if not optname:
1090 e = self._handle_error(e, fpname, lineno, line)
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001091 optname = self.optionxform(optname.rstrip())
Fred Drakea4923622010-08-09 12:52:45 +00001092 if (self._strict and
1093 (sectname, optname) in elements_added):
1094 raise DuplicateOptionError(sectname, optname,
1095 fpname, lineno)
1096 elements_added.add((sectname, optname))
Fred Drake03c44a32010-02-19 06:08:41 +00001097 # This check is fine because the OPTCRE cannot
1098 # match if it would set optval to None
1099 if optval is not None:
Fred Drake03c44a32010-02-19 06:08:41 +00001100 optval = optval.strip()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001101 cursect[optname] = [optval]
1102 else:
1103 # valueless option handling
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001104 cursect[optname] = None
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001105 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001106 # a non-fatal parsing error occurred. set up the
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001107 # exception but keep going. the exception will be
1108 # raised at the end of the file and will contain a
1109 # list of all bogus lines
Georg Brandl96a60ae2010-07-28 13:13:46 +00001110 e = self._handle_error(e, fpname, lineno, line)
Łukasz Langa47a9a4b2016-11-26 14:00:39 -08001111 self._join_multiline_values()
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001112 # if any parsing errors occurred, raise an exception
1113 if e:
1114 raise e
Fred Drakefce65572002-10-25 18:08:18 +00001115
Georg Brandl96a60ae2010-07-28 13:13:46 +00001116 def _join_multiline_values(self):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001117 defaults = self.default_section, self._defaults
1118 all_sections = itertools.chain((defaults,),
1119 self._sections.items())
1120 for section, options in all_sections:
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001121 for name, val in options.items():
1122 if isinstance(val, list):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001123 val = '\n'.join(val).rstrip()
1124 options[name] = self._interpolation.before_read(self,
1125 section,
1126 name, val)
Fred Drakefce65572002-10-25 18:08:18 +00001127
Łukasz Langaa5fab172017-08-24 09:43:53 -07001128 def _read_defaults(self, defaults):
1129 """Read the defaults passed in the initializer.
1130 Note: values can be non-string."""
1131 for key, value in defaults.items():
1132 self._defaults[self.optionxform(key)] = value
1133
Georg Brandl96a60ae2010-07-28 13:13:46 +00001134 def _handle_error(self, exc, fpname, lineno, line):
1135 if not exc:
1136 exc = ParsingError(fpname)
1137 exc.append(lineno, repr(line))
1138 return exc
1139
Fred Drakecc645b92010-09-04 04:35:34 +00001140 def _unify_values(self, section, vars):
Raymond Hettingerddb52402011-02-21 19:42:11 +00001141 """Create a sequence of lookups with 'vars' taking priority over
1142 the 'section' which takes priority over the DEFAULTSECT.
1143
Fred Drakefce65572002-10-25 18:08:18 +00001144 """
Raymond Hettingerddb52402011-02-21 19:42:11 +00001145 sectiondict = {}
Fred Drakefce65572002-10-25 18:08:18 +00001146 try:
Raymond Hettingerddb52402011-02-21 19:42:11 +00001147 sectiondict = self._sections[section]
Fred Drakefce65572002-10-25 18:08:18 +00001148 except KeyError:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001149 if section != self.default_section:
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001150 raise NoSectionError(section) from None
Fred Drakefce65572002-10-25 18:08:18 +00001151 # Update with the entry specific variables
Raymond Hettingerddb52402011-02-21 19:42:11 +00001152 vardict = {}
David Goodger68a1abd2004-10-03 15:40:25 +00001153 if vars:
1154 for key, value in vars.items():
Fred Drakecc645b92010-09-04 04:35:34 +00001155 if value is not None:
1156 value = str(value)
Raymond Hettingerddb52402011-02-21 19:42:11 +00001157 vardict[self.optionxform(key)] = value
1158 return _ChainMap(vardict, sectiondict, self._defaults)
Fred Drakecc645b92010-09-04 04:35:34 +00001159
1160 def _convert_to_boolean(self, value):
1161 """Return a boolean value translating from other types if necessary.
1162 """
1163 if value.lower() not in self.BOOLEAN_STATES:
1164 raise ValueError('Not a boolean: %s' % value)
1165 return self.BOOLEAN_STATES[value.lower()]
1166
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001167 def _validate_value_types(self, *, section="", option="", value=""):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001168 """Raises a TypeError for non-string values.
1169
1170 The only legal non-string value if we allow valueless
1171 options is None, so we need to check if the value is a
1172 string if:
1173 - we do not allow valueless options, or
1174 - we allow valueless options but the value is not None
1175
1176 For compatibility reasons this method is not used in classic set()
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001177 for RawConfigParsers. It is invoked in every case for mapping protocol
1178 access and in ConfigParser.set().
Łukasz Langa26d513c2010-11-10 18:57:39 +00001179 """
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001180 if not isinstance(section, str):
1181 raise TypeError("section names must be strings")
1182 if not isinstance(option, str):
1183 raise TypeError("option keys must be strings")
Łukasz Langa26d513c2010-11-10 18:57:39 +00001184 if not self._allow_no_value or value:
1185 if not isinstance(value, str):
1186 raise TypeError("option values must be strings")
1187
Łukasz Langadfdd2f72014-09-15 02:08:41 -07001188 @property
1189 def converters(self):
1190 return self._converters
1191
Łukasz Langa26d513c2010-11-10 18:57:39 +00001192
Fred Drakecc645b92010-09-04 04:35:34 +00001193class ConfigParser(RawConfigParser):
1194 """ConfigParser implementing interpolation."""
1195
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001196 _DEFAULT_INTERPOLATION = BasicInterpolation()
David Goodger1cbf2062004-10-03 15:55:09 +00001197
Fred Drake03c44a32010-02-19 06:08:41 +00001198 def set(self, section, option, value=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001199 """Set an option. Extends RawConfigParser.set by validating type and
1200 interpolation syntax on the value."""
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001201 self._validate_value_types(option=option, value=value)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001202 super().set(section, option, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001203
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001204 def add_section(self, section):
1205 """Create a new section in the configuration. Extends
1206 RawConfigParser.add_section by validating if the section name is
1207 a string."""
1208 self._validate_value_types(section=section)
1209 super().add_section(section)
1210
Łukasz Langaa5fab172017-08-24 09:43:53 -07001211 def _read_defaults(self, defaults):
1212 """Reads the defaults passed in the initializer, implicitly converting
Łukasz Langa214f18e2018-06-08 04:02:48 -07001213 values to strings like the rest of the API.
1214
1215 Does not perform interpolation for backwards compatibility.
1216 """
1217 try:
1218 hold_interpolation = self._interpolation
1219 self._interpolation = Interpolation()
1220 self.read_dict({self.default_section: defaults})
1221 finally:
1222 self._interpolation = hold_interpolation
Łukasz Langaa5fab172017-08-24 09:43:53 -07001223
Łukasz Langa26d513c2010-11-10 18:57:39 +00001224
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001225class SafeConfigParser(ConfigParser):
1226 """ConfigParser alias for backwards compatibility purposes."""
1227
1228 def __init__(self, *args, **kwargs):
1229 super().__init__(*args, **kwargs)
1230 warnings.warn(
1231 "The SafeConfigParser class has been renamed to ConfigParser "
1232 "in Python 3.2. This alias will be removed in future versions."
1233 " Use ConfigParser directly instead.",
1234 DeprecationWarning, stacklevel=2
1235 )
1236
1237
Łukasz Langa26d513c2010-11-10 18:57:39 +00001238class SectionProxy(MutableMapping):
1239 """A proxy for a single section from a parser."""
1240
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001241 def __init__(self, parser, name):
1242 """Creates a view on a section of the specified `name` in `parser`."""
Łukasz Langa26d513c2010-11-10 18:57:39 +00001243 self._parser = parser
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001244 self._name = name
Łukasz Langadfdd2f72014-09-15 02:08:41 -07001245 for conv in parser.converters:
1246 key = 'get' + conv
1247 getter = functools.partial(self.get, _impl=getattr(parser, key))
1248 setattr(self, key, getter)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001249
1250 def __repr__(self):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001251 return '<Section: {}>'.format(self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001252
1253 def __getitem__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001254 if not self._parser.has_option(self._name, key):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001255 raise KeyError(key)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001256 return self._parser.get(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001257
1258 def __setitem__(self, key, value):
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001259 self._parser._validate_value_types(option=key, value=value)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001260 return self._parser.set(self._name, key, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001261
1262 def __delitem__(self, key):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001263 if not (self._parser.has_option(self._name, key) and
1264 self._parser.remove_option(self._name, key)):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001265 raise KeyError(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001266
1267 def __contains__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001268 return self._parser.has_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001269
1270 def __len__(self):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001271 return len(self._options())
Łukasz Langa26d513c2010-11-10 18:57:39 +00001272
1273 def __iter__(self):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001274 return self._options().__iter__()
1275
1276 def _options(self):
1277 if self._name != self._parser.default_section:
1278 return self._parser.options(self._name)
1279 else:
1280 return self._parser.defaults()
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001281
1282 @property
1283 def parser(self):
1284 # The parser object of the proxy is read-only.
1285 return self._parser
1286
1287 @property
1288 def name(self):
1289 # The name of the section on a proxy is read-only.
1290 return self._name
Łukasz Langadfdd2f72014-09-15 02:08:41 -07001291
1292 def get(self, option, fallback=None, *, raw=False, vars=None,
1293 _impl=None, **kwargs):
1294 """Get an option value.
1295
1296 Unless `fallback` is provided, `None` will be returned if the option
1297 is not found.
1298
1299 """
1300 # If `_impl` is provided, it should be a getter method on the parser
1301 # object that provides the desired type conversion.
1302 if not _impl:
1303 _impl = self._parser.get
1304 return _impl(self._name, option, raw=raw, vars=vars,
1305 fallback=fallback, **kwargs)
1306
1307
1308class ConverterMapping(MutableMapping):
1309 """Enables reuse of get*() methods between the parser and section proxies.
1310
1311 If a parser class implements a getter directly, the value for the given
1312 key will be ``None``. The presence of the converter name here enables
1313 section proxies to find and use the implementation on the parser class.
1314 """
1315
1316 GETTERCRE = re.compile(r"^get(?P<name>.+)$")
1317
1318 def __init__(self, parser):
1319 self._parser = parser
1320 self._data = {}
1321 for getter in dir(self._parser):
1322 m = self.GETTERCRE.match(getter)
1323 if not m or not callable(getattr(self._parser, getter)):
1324 continue
1325 self._data[m.group('name')] = None # See class docstring.
1326
1327 def __getitem__(self, key):
1328 return self._data[key]
1329
1330 def __setitem__(self, key, value):
1331 try:
1332 k = 'get' + key
1333 except TypeError:
1334 raise ValueError('Incompatible key: {} (type: {})'
1335 ''.format(key, type(key)))
1336 if k == 'get':
1337 raise ValueError('Incompatible key: cannot use "" as a name')
1338 self._data[key] = value
1339 func = functools.partial(self._parser._get_conv, conv=value)
1340 func.converter = value
1341 setattr(self._parser, k, func)
1342 for proxy in self._parser.values():
1343 getter = functools.partial(proxy.get, _impl=func)
1344 setattr(proxy, k, getter)
1345
1346 def __delitem__(self, key):
1347 try:
1348 k = 'get' + (key or None)
1349 except TypeError:
1350 raise KeyError(key)
1351 del self._data[key]
1352 for inst in itertools.chain((self._parser,), self._parser.values()):
1353 try:
1354 delattr(inst, k)
1355 except AttributeError:
1356 # don't raise since the entry was present in _data, silently
1357 # clean up
1358 continue
1359
1360 def __iter__(self):
1361 return iter(self._data)
1362
1363 def __len__(self):
1364 return len(self._data)