blob: 33dc9b9046f102a414b41a26389e5306b2107330 [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
59 pre-processing when using getters. RawConfigParser object s don't do
60 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)
Georg Brandl96a60ae2010-07-28 13:13:46 +000083 Read and parse the list 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
Raymond Hettinger9fe1ccf2011-02-26 01:02:51 +0000142from collections import OrderedDict as _default_dict, 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
Guido van Rossum3d209861997-12-09 16:10:31 +0000160DEFAULTSECT = "DEFAULT"
161
Fred Drake2a37f9f2000-09-27 22:43:54 +0000162MAX_INTERPOLATION_DEPTH = 10
163
Guido van Rossum3d209861997-12-09 16:10:31 +0000164
Tim Peters88869f92001-01-14 23:36:06 +0000165
Guido van Rossum3d209861997-12-09 16:10:31 +0000166# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000167class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000168 """Base class for ConfigParser exceptions."""
169
Guido van Rossum3d209861997-12-09 16:10:31 +0000170 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000171 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000172 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000173
Guido van Rossum3d209861997-12-09 16:10:31 +0000174 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000175 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000176
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000177 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000178
Georg Brandl96a60ae2010-07-28 13:13:46 +0000179
Guido van Rossum3d209861997-12-09 16:10:31 +0000180class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000181 """Raised when no section matches a requested option."""
182
Guido van Rossum3d209861997-12-09 16:10:31 +0000183 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000184 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000185 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000186 self.args = (section, )
Guido van Rossum3d209861997-12-09 16:10:31 +0000187
Georg Brandl96a60ae2010-07-28 13:13:46 +0000188
Guido van Rossum3d209861997-12-09 16:10:31 +0000189class DuplicateSectionError(Error):
Fred Drakea4923622010-08-09 12:52:45 +0000190 """Raised when a section is repeated in an input source.
Fred Drake8d5dd982002-12-30 23:51:45 +0000191
Fred Drakea4923622010-08-09 12:52:45 +0000192 Possible repetitions that raise this exception are: multiple creation
193 using the API or in strict parsers when a section is found more than once
194 in a single input file, string or dictionary.
195 """
196
197 def __init__(self, section, source=None, lineno=None):
198 msg = [repr(section), " already exists"]
199 if source is not None:
Łukasz Langaf9b4eb42013-06-23 19:10:25 +0200200 message = ["While reading from ", repr(source)]
Fred Drakea4923622010-08-09 12:52:45 +0000201 if lineno is not None:
202 message.append(" [line {0:2d}]".format(lineno))
203 message.append(": section ")
204 message.extend(msg)
205 msg = message
206 else:
207 msg.insert(0, "Section ")
208 Error.__init__(self, "".join(msg))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000209 self.section = section
Fred Drakea4923622010-08-09 12:52:45 +0000210 self.source = source
211 self.lineno = lineno
212 self.args = (section, source, lineno)
213
214
215class DuplicateOptionError(Error):
216 """Raised by strict parsers when an option is repeated in an input source.
217
218 Current implementation raises this exception only when an option is found
219 more than once in a single file, string or dictionary.
220 """
221
222 def __init__(self, section, option, source=None, lineno=None):
223 msg = [repr(option), " in section ", repr(section),
224 " already exists"]
225 if source is not None:
Łukasz Langaf9b4eb42013-06-23 19:10:25 +0200226 message = ["While reading from ", repr(source)]
Fred Drakea4923622010-08-09 12:52:45 +0000227 if lineno is not None:
228 message.append(" [line {0:2d}]".format(lineno))
229 message.append(": option ")
230 message.extend(msg)
231 msg = message
232 else:
233 msg.insert(0, "Option ")
234 Error.__init__(self, "".join(msg))
235 self.section = section
236 self.option = option
237 self.source = source
238 self.lineno = lineno
239 self.args = (section, option, source, lineno)
Guido van Rossum3d209861997-12-09 16:10:31 +0000240
Georg Brandl96a60ae2010-07-28 13:13:46 +0000241
Guido van Rossum3d209861997-12-09 16:10:31 +0000242class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000243 """A requested option was not found."""
244
Guido van Rossum3d209861997-12-09 16:10:31 +0000245 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000246 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000247 (option, section))
248 self.option = option
249 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000250 self.args = (option, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000251
Georg Brandl96a60ae2010-07-28 13:13:46 +0000252
Guido van Rossum3d209861997-12-09 16:10:31 +0000253class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000254 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000255
Fred Drakee2c64912002-12-31 17:23:27 +0000256 def __init__(self, option, section, msg):
257 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000258 self.option = option
259 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000260 self.args = (option, section, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000261
Georg Brandl96a60ae2010-07-28 13:13:46 +0000262
Fred Drakee2c64912002-12-31 17:23:27 +0000263class InterpolationMissingOptionError(InterpolationError):
264 """A string substitution required a setting which was not available."""
265
266 def __init__(self, option, section, rawval, reference):
Robert Collinsac37ba02015-08-14 11:11:35 +1200267 msg = ("Bad value substitution: option {!r} in section {!r} contains "
268 "an interpolation key {!r} which is not a valid option name. "
269 "Raw value: {!r}".format(option, section, reference, rawval))
Fred Drakee2c64912002-12-31 17:23:27 +0000270 InterpolationError.__init__(self, option, section, msg)
271 self.reference = reference
Michael Foordbd6c0792010-07-25 23:09:25 +0000272 self.args = (option, section, rawval, reference)
Fred Drakee2c64912002-12-31 17:23:27 +0000273
Georg Brandl96a60ae2010-07-28 13:13:46 +0000274
Fred Drakee2c64912002-12-31 17:23:27 +0000275class InterpolationSyntaxError(InterpolationError):
Fred Drakea4923622010-08-09 12:52:45 +0000276 """Raised when the source text contains invalid syntax.
277
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000278 Current implementation raises this exception when the source text into
279 which substitutions are made does not conform to the required syntax.
Fred Drakea4923622010-08-09 12:52:45 +0000280 """
Neal Norwitzce1d9442002-12-30 23:38:47 +0000281
Georg Brandl96a60ae2010-07-28 13:13:46 +0000282
Fred Drakee2c64912002-12-31 17:23:27 +0000283class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000284 """Raised when substitutions are nested too deeply."""
285
Fred Drake2a37f9f2000-09-27 22:43:54 +0000286 def __init__(self, option, section, rawval):
Robert Collinsac37ba02015-08-14 11:11:35 +1200287 msg = ("Recursion limit exceeded in value substitution: option {!r} "
288 "in section {!r} contains an interpolation key which "
289 "cannot be substituted in {} steps. Raw value: {!r}"
290 "".format(option, section, MAX_INTERPOLATION_DEPTH,
291 rawval))
Fred Drakee2c64912002-12-31 17:23:27 +0000292 InterpolationError.__init__(self, option, section, msg)
Michael Foordbd6c0792010-07-25 23:09:25 +0000293 self.args = (option, section, rawval)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000294
Georg Brandl96a60ae2010-07-28 13:13:46 +0000295
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000296class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000297 """Raised when a configuration file does not follow legal syntax."""
298
Fred Drakea4923622010-08-09 12:52:45 +0000299 def __init__(self, source=None, filename=None):
300 # Exactly one of `source'/`filename' arguments has to be given.
301 # `filename' kept for compatibility.
302 if filename and source:
303 raise ValueError("Cannot specify both `filename' and `source'. "
304 "Use `source'.")
305 elif not filename and not source:
306 raise ValueError("Required argument `source' not given.")
307 elif filename:
308 source = filename
Serhiy Storchakabc27a052014-02-06 22:49:45 +0200309 Error.__init__(self, 'Source contains parsing errors: %r' % source)
Fred Drakea4923622010-08-09 12:52:45 +0000310 self.source = source
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000311 self.errors = []
Fred Drakea4923622010-08-09 12:52:45 +0000312 self.args = (source, )
313
314 @property
315 def filename(self):
316 """Deprecated, use `source'."""
317 warnings.warn(
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000318 "The 'filename' attribute will be removed in future versions. "
Fred Drakea4923622010-08-09 12:52:45 +0000319 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000320 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000321 )
322 return self.source
323
324 @filename.setter
325 def filename(self, value):
326 """Deprecated, user `source'."""
327 warnings.warn(
328 "The 'filename' attribute will be removed in future versions. "
329 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000330 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000331 )
332 self.source = value
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000333
334 def append(self, lineno, line):
335 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000336 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000337
Georg Brandl96a60ae2010-07-28 13:13:46 +0000338
Fred Drake2a37f9f2000-09-27 22:43:54 +0000339class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000340 """Raised when a key-value pair is found before any section header."""
341
Fred Drake2a37f9f2000-09-27 22:43:54 +0000342 def __init__(self, filename, lineno, line):
343 Error.__init__(
344 self,
Serhiy Storchakabc27a052014-02-06 22:49:45 +0200345 'File contains no section headers.\nfile: %r, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000346 (filename, lineno, line))
Fred Drakea4923622010-08-09 12:52:45 +0000347 self.source = filename
Fred Drake2a37f9f2000-09-27 22:43:54 +0000348 self.lineno = lineno
349 self.line = line
Michael Foordbd6c0792010-07-25 23:09:25 +0000350 self.args = (filename, lineno, line)
Guido van Rossum3d209861997-12-09 16:10:31 +0000351
Georg Brandl96a60ae2010-07-28 13:13:46 +0000352
Fred Drakecc645b92010-09-04 04:35:34 +0000353# Used in parser getters to indicate the default behaviour when a specific
354# option is not found it to raise an exception. Created to enable `None' as
355# a valid fallback value.
356_UNSET = object()
357
358
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000359class Interpolation:
360 """Dummy interpolation that passes the value through with no changes."""
361
362 def before_get(self, parser, section, option, value, defaults):
363 return value
364
365 def before_set(self, parser, section, option, value):
366 return value
367
368 def before_read(self, parser, section, option, value):
369 return value
370
371 def before_write(self, parser, section, option, value):
372 return value
373
374
375class BasicInterpolation(Interpolation):
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000376 """Interpolation as implemented in the classic ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000377
378 The option values can contain format strings which refer to other values in
379 the same section, or values in the special default section.
380
381 For example:
382
383 something: %(dir)s/whatever
384
385 would resolve the "%(dir)s" to the value of dir. All reference
386 expansions are done late, on demand. If a user needs to use a bare % in
Ezio Melottie130a522011-10-19 10:58:56 +0300387 a configuration file, she can escape it by writing %%. Other % usage
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000388 is considered a user error and raises `InterpolationSyntaxError'."""
389
390 _KEYCRE = re.compile(r"%\(([^)]+)\)s")
391
392 def before_get(self, parser, section, option, value, defaults):
393 L = []
394 self._interpolate_some(parser, option, L, value, section, defaults, 1)
395 return ''.join(L)
396
397 def before_set(self, parser, section, option, value):
398 tmp_value = value.replace('%%', '') # escaped percent signs
399 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
400 if '%' in tmp_value:
401 raise ValueError("invalid interpolation syntax in %r at "
402 "position %d" % (value, tmp_value.find('%')))
403 return value
404
405 def _interpolate_some(self, parser, option, accum, rest, section, map,
406 depth):
Robert Collinsac37ba02015-08-14 11:11:35 +1200407 rawval = parser.get(section, option, raw=True, fallback=rest)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000408 if depth > MAX_INTERPOLATION_DEPTH:
Robert Collinsac37ba02015-08-14 11:11:35 +1200409 raise InterpolationDepthError(option, section, rawval)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000410 while rest:
411 p = rest.find("%")
412 if p < 0:
413 accum.append(rest)
414 return
415 if p > 0:
416 accum.append(rest[:p])
417 rest = rest[p:]
418 # p is no longer used
419 c = rest[1:2]
420 if c == "%":
421 accum.append("%")
422 rest = rest[2:]
423 elif c == "(":
424 m = self._KEYCRE.match(rest)
425 if m is None:
426 raise InterpolationSyntaxError(option, section,
427 "bad interpolation variable reference %r" % rest)
428 var = parser.optionxform(m.group(1))
429 rest = rest[m.end():]
430 try:
431 v = map[var]
432 except KeyError:
433 raise InterpolationMissingOptionError(
Robert Collinsf7a92672015-08-14 11:47:41 +1200434 option, section, rawval, var) from None
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000435 if "%" in v:
436 self._interpolate_some(parser, option, accum, v,
437 section, map, depth + 1)
438 else:
439 accum.append(v)
440 else:
441 raise InterpolationSyntaxError(
442 option, section,
443 "'%%' must be followed by '%%' or '(', "
444 "found: %r" % (rest,))
445
446
447class ExtendedInterpolation(Interpolation):
448 """Advanced variant of interpolation, supports the syntax used by
449 `zc.buildout'. Enables interpolation between sections."""
450
451 _KEYCRE = re.compile(r"\$\{([^}]+)\}")
452
453 def before_get(self, parser, section, option, value, defaults):
454 L = []
455 self._interpolate_some(parser, option, L, value, section, defaults, 1)
456 return ''.join(L)
457
458 def before_set(self, parser, section, option, value):
459 tmp_value = value.replace('$$', '') # escaped dollar signs
460 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
461 if '$' in tmp_value:
462 raise ValueError("invalid interpolation syntax in %r at "
Łukasz Langafa608182013-04-24 01:25:18 +0200463 "position %d" % (value, tmp_value.find('$')))
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000464 return value
465
466 def _interpolate_some(self, parser, option, accum, rest, section, map,
467 depth):
Robert Collinsac37ba02015-08-14 11:11:35 +1200468 rawval = parser.get(section, option, raw=True, fallback=rest)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000469 if depth > MAX_INTERPOLATION_DEPTH:
Robert Collinsac37ba02015-08-14 11:11:35 +1200470 raise InterpolationDepthError(option, section, rawval)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000471 while rest:
472 p = rest.find("$")
473 if p < 0:
474 accum.append(rest)
475 return
476 if p > 0:
477 accum.append(rest[:p])
478 rest = rest[p:]
479 # p is no longer used
480 c = rest[1:2]
481 if c == "$":
482 accum.append("$")
483 rest = rest[2:]
484 elif c == "{":
485 m = self._KEYCRE.match(rest)
486 if m is None:
487 raise InterpolationSyntaxError(option, section,
488 "bad interpolation variable reference %r" % rest)
Łukasz Langae698cd52011-04-28 10:58:57 +0200489 path = m.group(1).split(':')
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000490 rest = rest[m.end():]
491 sect = section
492 opt = option
493 try:
494 if len(path) == 1:
Łukasz Langae698cd52011-04-28 10:58:57 +0200495 opt = parser.optionxform(path[0])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000496 v = map[opt]
497 elif len(path) == 2:
498 sect = path[0]
Łukasz Langae698cd52011-04-28 10:58:57 +0200499 opt = parser.optionxform(path[1])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000500 v = parser.get(sect, opt, raw=True)
501 else:
502 raise InterpolationSyntaxError(
503 option, section,
504 "More than one ':' found: %r" % (rest,))
Łukasz Langa71b37a52010-12-17 21:56:32 +0000505 except (KeyError, NoSectionError, NoOptionError):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000506 raise InterpolationMissingOptionError(
Robert Collinsf7a92672015-08-14 11:47:41 +1200507 option, section, rawval, ":".join(path)) from None
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000508 if "$" in v:
509 self._interpolate_some(parser, opt, accum, v, sect,
510 dict(parser.items(sect, raw=True)),
511 depth + 1)
512 else:
513 accum.append(v)
514 else:
515 raise InterpolationSyntaxError(
516 option, section,
517 "'$' must be followed by '$' or '{', "
518 "found: %r" % (rest,))
519
520
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000521class LegacyInterpolation(Interpolation):
522 """Deprecated interpolation used in old versions of ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000523 Use BasicInterpolation or ExtendedInterpolation instead."""
524
525 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
526
527 def before_get(self, parser, section, option, value, vars):
528 rawval = value
529 depth = MAX_INTERPOLATION_DEPTH
530 while depth: # Loop through this until it's done
531 depth -= 1
532 if value and "%(" in value:
533 replace = functools.partial(self._interpolation_replace,
534 parser=parser)
535 value = self._KEYCRE.sub(replace, value)
536 try:
537 value = value % vars
538 except KeyError as e:
539 raise InterpolationMissingOptionError(
Łukasz Langa949053b2014-09-04 01:36:33 -0700540 option, section, rawval, e.args[0]) from None
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000541 else:
542 break
543 if value and "%(" in value:
544 raise InterpolationDepthError(option, section, rawval)
545 return value
546
547 def before_set(self, parser, section, option, value):
548 return value
549
550 @staticmethod
551 def _interpolation_replace(match, parser):
552 s = match.group(1)
553 if s is None:
554 return match.group()
555 else:
556 return "%%(%s)s" % parser.optionxform(s)
557
558
Łukasz Langa26d513c2010-11-10 18:57:39 +0000559class RawConfigParser(MutableMapping):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000560 """ConfigParser that does not do interpolation."""
561
562 # Regular expressions for parsing section headers and options
563 _SECT_TMPL = r"""
564 \[ # [
565 (?P<header>[^]]+) # very permissive!
566 \] # ]
567 """
568 _OPT_TMPL = r"""
569 (?P<option>.*?) # very permissive!
570 \s*(?P<vi>{delim})\s* # any number of space/tab,
571 # followed by any of the
572 # allowed delimiters,
573 # followed by any space/tab
574 (?P<value>.*)$ # everything up to eol
575 """
576 _OPT_NV_TMPL = r"""
577 (?P<option>.*?) # very permissive!
578 \s*(?: # any number of space/tab,
579 (?P<vi>{delim})\s* # optionally followed by
580 # any of the allowed
581 # delimiters, followed by any
582 # space/tab
583 (?P<value>.*))?$ # everything up to eol
584 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000585 # Interpolation algorithm to be used if the user does not specify another
586 _DEFAULT_INTERPOLATION = Interpolation()
Georg Brandl96a60ae2010-07-28 13:13:46 +0000587 # Compiled regular expression for matching sections
588 SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
589 # Compiled regular expression for matching options with typical separators
590 OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
591 # Compiled regular expression for matching options with optional values
592 # delimited using typical separators
593 OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
594 # Compiled regular expression for matching leading whitespace in a line
595 NONSPACECRE = re.compile(r"\S")
Fred Drakecc645b92010-09-04 04:35:34 +0000596 # Possible boolean values in the configuration.
597 BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
598 '0': False, 'no': False, 'false': False, 'off': False}
Georg Brandl96a60ae2010-07-28 13:13:46 +0000599
Fred Drake03c44a32010-02-19 06:08:41 +0000600 def __init__(self, defaults=None, dict_type=_default_dict,
Fred Drakea4923622010-08-09 12:52:45 +0000601 allow_no_value=False, *, delimiters=('=', ':'),
Łukasz Langab25a7912010-12-17 01:32:29 +0000602 comment_prefixes=('#', ';'), inline_comment_prefixes=None,
603 strict=True, empty_lines_in_values=True,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000604 default_section=DEFAULTSECT,
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700605 interpolation=_UNSET, converters=_UNSET):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000606
Thomas Wouters89f507f2006-12-13 04:49:30 +0000607 self._dict = dict_type
608 self._sections = self._dict()
609 self._defaults = self._dict()
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700610 self._converters = ConverterMapping(self)
Łukasz Langa49afa382010-11-11 19:53:23 +0000611 self._proxies = self._dict()
Łukasz Langac264c092010-11-20 16:15:37 +0000612 self._proxies[default_section] = SectionProxy(self, default_section)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000613 self._delimiters = tuple(delimiters)
614 if delimiters == ('=', ':'):
615 self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
616 else:
Fred Drakea4923622010-08-09 12:52:45 +0000617 d = "|".join(re.escape(d) for d in delimiters)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000618 if allow_no_value:
Fred Drakea4923622010-08-09 12:52:45 +0000619 self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000620 re.VERBOSE)
621 else:
Fred Drakea4923622010-08-09 12:52:45 +0000622 self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000623 re.VERBOSE)
Łukasz Langab25a7912010-12-17 01:32:29 +0000624 self._comment_prefixes = tuple(comment_prefixes or ())
625 self._inline_comment_prefixes = tuple(inline_comment_prefixes or ())
Fred Drakea4923622010-08-09 12:52:45 +0000626 self._strict = strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000627 self._allow_no_value = allow_no_value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000628 self._empty_lines_in_values = empty_lines_in_values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000629 self.default_section=default_section
Łukasz Langa1aa422f2011-04-28 17:03:45 +0200630 self._interpolation = interpolation
631 if self._interpolation is _UNSET:
632 self._interpolation = self._DEFAULT_INTERPOLATION
633 if self._interpolation is None:
634 self._interpolation = Interpolation()
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700635 if converters is not _UNSET:
636 self._converters.update(converters)
James Tocknell44e6ad82017-08-22 08:46:30 +1000637 if defaults:
Łukasz Langaa5fab172017-08-24 09:43:53 -0700638 self._read_defaults(defaults)
Guido van Rossum3d209861997-12-09 16:10:31 +0000639
640 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000641 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000642
643 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000644 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000645 # self._sections will never have [DEFAULT] in it
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000646 return list(self._sections.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000647
648 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000649 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000650
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000651 Raise DuplicateSectionError if a section by the specified name
Łukasz Langac264c092010-11-20 16:15:37 +0000652 already exists. Raise ValueError if name is DEFAULT.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000653 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000654 if section == self.default_section:
Łukasz Langa3a11e712010-12-03 22:15:19 +0000655 raise ValueError('Invalid section name: %r' % section)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000656
Fred Drakefce65572002-10-25 18:08:18 +0000657 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000658 raise DuplicateSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000659 self._sections[section] = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000660 self._proxies[section] = SectionProxy(self, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000661
662 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000663 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000664
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000665 The DEFAULT section is not acknowledged.
666 """
Fred Drakefce65572002-10-25 18:08:18 +0000667 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000668
669 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000670 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000671 try:
Fred Drakefce65572002-10-25 18:08:18 +0000672 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000673 except KeyError:
Łukasz Langa949053b2014-09-04 01:36:33 -0700674 raise NoSectionError(section) from None
Fred Drakefce65572002-10-25 18:08:18 +0000675 opts.update(self._defaults)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000676 return list(opts.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000677
Georg Brandl8dcaa732010-07-29 12:17:40 +0000678 def read(self, filenames, encoding=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000679 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000680
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000681 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000682 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000683 configuration file locations (e.g. current directory, user's
684 home directory, systemwide directory), and all existing
685 configuration files in the list will be read. A single
686 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000687
688 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000689 """
Vincent Michele3148532017-11-02 13:47:04 +0100690 if isinstance(filenames, (str, bytes, os.PathLike)):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000691 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000692 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000693 for filename in filenames:
694 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000695 with open(filename, encoding=encoding) as fp:
696 self._read(fp, filename)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200697 except OSError:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000698 continue
David Ellis85b8d012017-03-03 17:14:27 +0000699 if isinstance(filename, os.PathLike):
700 filename = os.fspath(filename)
Fred Drake82903142004-05-18 04:24:02 +0000701 read_ok.append(filename)
702 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000703
Fred Drakea4923622010-08-09 12:52:45 +0000704 def read_file(self, f, source=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000705 """Like read() but the argument must be a file-like object.
706
Łukasz Langadaab1c82011-04-27 18:10:05 +0200707 The `f' argument must be iterable, returning one line at a time.
708 Optional second argument is the `source' specifying the name of the
709 file being read. If not given, it is taken from f.name. If `f' has no
710 `name' attribute, `<???>' is used.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000711 """
Fred Drakea4923622010-08-09 12:52:45 +0000712 if source is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000713 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000714 source = f.name
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000715 except AttributeError:
Fred Drakea4923622010-08-09 12:52:45 +0000716 source = '<???>'
717 self._read(f, source)
718
719 def read_string(self, string, source='<string>'):
720 """Read configuration from a given string."""
721 sfile = io.StringIO(string)
722 self.read_file(sfile, source)
723
724 def read_dict(self, dictionary, source='<dict>'):
725 """Read configuration from a dictionary.
726
727 Keys are section names, values are dictionaries with keys and values
728 that should be present in the section. If the used dictionary type
729 preserves order, sections and their keys will be added in order.
730
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000731 All types held in the dictionary are converted to strings during
732 reading, including section names, option names and keys.
733
Fred Drakea4923622010-08-09 12:52:45 +0000734 Optional second argument is the `source' specifying the name of the
735 dictionary being read.
736 """
737 elements_added = set()
738 for section, keys in dictionary.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000739 section = str(section)
Fred Drakea4923622010-08-09 12:52:45 +0000740 try:
741 self.add_section(section)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000742 except (DuplicateSectionError, ValueError):
Fred Drakea4923622010-08-09 12:52:45 +0000743 if self._strict and section in elements_added:
744 raise
Łukasz Langa71b37a52010-12-17 21:56:32 +0000745 elements_added.add(section)
Fred Drakea4923622010-08-09 12:52:45 +0000746 for key, value in keys.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000747 key = self.optionxform(str(key))
Fred Drakecc645b92010-09-04 04:35:34 +0000748 if value is not None:
749 value = str(value)
Fred Drakea4923622010-08-09 12:52:45 +0000750 if self._strict and (section, key) in elements_added:
751 raise DuplicateOptionError(section, key, source)
752 elements_added.add((section, key))
753 self.set(section, key, value)
754
755 def readfp(self, fp, filename=None):
756 """Deprecated, use read_file instead."""
757 warnings.warn(
758 "This method will be removed in future versions. "
759 "Use 'parser.read_file()' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000760 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000761 )
762 self.read_file(fp, source=filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000763
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000764 def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000765 """Get an option value for a given section.
766
767 If `vars' is provided, it must be a dictionary. The option is looked up
768 in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000769 If the key is not found and `fallback' is provided, it is used as
770 a fallback value. `None' can be provided as a `fallback' value.
771
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000772 If interpolation is enabled and the optional argument `raw' is False,
773 all interpolations are expanded in the return values.
774
775 Arguments `raw', `vars', and `fallback' are keyword only.
776
777 The section DEFAULT is special.
Fred Drakecc645b92010-09-04 04:35:34 +0000778 """
779 try:
780 d = self._unify_values(section, vars)
781 except NoSectionError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000782 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000783 raise
Fred Drakefce65572002-10-25 18:08:18 +0000784 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000785 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000786 option = self.optionxform(option)
787 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000788 value = d[option]
Fred Drakecc645b92010-09-04 04:35:34 +0000789 except KeyError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000790 if fallback is _UNSET:
Fred Drakefce65572002-10-25 18:08:18 +0000791 raise NoOptionError(option, section)
Fred Drakecc645b92010-09-04 04:35:34 +0000792 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000793 return fallback
Fred Drake2a37f9f2000-09-27 22:43:54 +0000794
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000795 if raw or value is None:
796 return value
797 else:
798 return self._interpolation.before_get(self, section, option, value,
799 d)
Fred Drake2ca041f2002-09-27 15:49:56 +0000800
Łukasz Langa26d513c2010-11-10 18:57:39 +0000801 def _get(self, section, conv, option, **kwargs):
802 return conv(self.get(section, option, **kwargs))
Guido van Rossum3d209861997-12-09 16:10:31 +0000803
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700804 def _get_conv(self, section, option, conv, *, raw=False, vars=None,
805 fallback=_UNSET, **kwargs):
Fred Drakecc645b92010-09-04 04:35:34 +0000806 try:
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700807 return self._get(section, conv, option, raw=raw, vars=vars,
808 **kwargs)
Fred Drakecc645b92010-09-04 04:35:34 +0000809 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000810 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000811 raise
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700812 return fallback
813
814 # getint, getfloat and getboolean provided directly for backwards compat
815 def getint(self, section, option, *, raw=False, vars=None,
816 fallback=_UNSET, **kwargs):
817 return self._get_conv(section, option, int, raw=raw, vars=vars,
818 fallback=fallback, **kwargs)
Guido van Rossum3d209861997-12-09 16:10:31 +0000819
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000820 def getfloat(self, section, option, *, raw=False, vars=None,
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700821 fallback=_UNSET, **kwargs):
822 return self._get_conv(section, option, float, raw=raw, vars=vars,
823 fallback=fallback, **kwargs)
Guido van Rossum3d209861997-12-09 16:10:31 +0000824
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000825 def getboolean(self, section, option, *, raw=False, vars=None,
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700826 fallback=_UNSET, **kwargs):
827 return self._get_conv(section, option, self._convert_to_boolean,
828 raw=raw, vars=vars, fallback=fallback, **kwargs)
Guido van Rossum3d209861997-12-09 16:10:31 +0000829
Łukasz Langa71b37a52010-12-17 21:56:32 +0000830 def items(self, section=_UNSET, raw=False, vars=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000831 """Return a list of (name, value) tuples for each option in a section.
832
833 All % interpolations are expanded in the return values, based on the
834 defaults passed into the constructor, unless the optional argument
835 `raw' is true. Additional substitutions may be provided using the
836 `vars' argument, which must be a dictionary whose contents overrides
837 any pre-existing defaults.
838
839 The section DEFAULT is special.
840 """
Łukasz Langa71b37a52010-12-17 21:56:32 +0000841 if section is _UNSET:
842 return super().items()
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000843 d = self._defaults.copy()
844 try:
845 d.update(self._sections[section])
846 except KeyError:
847 if section != self.default_section:
848 raise NoSectionError(section)
849 # Update with the entry specific variables
850 if vars:
851 for key, value in vars.items():
852 d[self.optionxform(key)] = value
Łukasz Langa24bcc612010-12-04 11:48:11 +0000853 value_getter = lambda option: self._interpolation.before_get(self,
854 section, option, d[option], d)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000855 if raw:
Łukasz Langa24bcc612010-12-04 11:48:11 +0000856 value_getter = lambda option: d[option]
857 return [(option, value_getter(option)) for option in d.keys()]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000858
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100859 def popitem(self):
860 """Remove a section from the parser and return it as
861 a (section_name, section_proxy) tuple. If no section is present, raise
862 KeyError.
863
864 The section DEFAULT is never returned because it cannot be removed.
865 """
866 for key in self.sections():
867 value = self[key]
868 del self[key]
869 return key, value
870 raise KeyError
871
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000872 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000873 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000874
Eric S. Raymond417c4892000-07-10 18:11:00 +0000875 def has_option(self, section, option):
Łukasz Langa71b37a52010-12-17 21:56:32 +0000876 """Check for the existence of a given option in a given section.
877 If the specified `section' is None or an empty string, DEFAULT is
878 assumed. If the specified `section' does not exist, returns False."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000879 if not section or section == self.default_section:
Fred Drakec2ff9052002-09-27 15:33:11 +0000880 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000881 return option in self._defaults
882 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000883 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000884 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000885 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000886 return (option in self._sections[section]
887 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000888
Fred Drake03c44a32010-02-19 06:08:41 +0000889 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000890 """Set an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000891 if value:
892 value = self._interpolation.before_set(self, section, option,
893 value)
894 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000895 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000896 else:
897 try:
Fred Drakefce65572002-10-25 18:08:18 +0000898 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000899 except KeyError:
Łukasz Langa949053b2014-09-04 01:36:33 -0700900 raise NoSectionError(section) from None
Fred Drakec2ff9052002-09-27 15:33:11 +0000901 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000902
Georg Brandl96a60ae2010-07-28 13:13:46 +0000903 def write(self, fp, space_around_delimiters=True):
904 """Write an .ini-format representation of the configuration state.
905
906 If `space_around_delimiters' is True (the default), delimiters
907 between keys and values are surrounded by spaces.
908 """
909 if space_around_delimiters:
910 d = " {} ".format(self._delimiters[0])
911 else:
912 d = self._delimiters[0]
Fred Drakefce65572002-10-25 18:08:18 +0000913 if self._defaults:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000914 self._write_section(fp, self.default_section,
Łukasz Langac264c092010-11-20 16:15:37 +0000915 self._defaults.items(), d)
Fred Drakefce65572002-10-25 18:08:18 +0000916 for section in self._sections:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000917 self._write_section(fp, section,
918 self._sections[section].items(), d)
919
920 def _write_section(self, fp, section_name, section_items, delimiter):
921 """Write a single section to the specified `fp'."""
922 fp.write("[{}]\n".format(section_name))
923 for key, value in section_items:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000924 value = self._interpolation.before_write(self, section_name, key,
925 value)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000926 if value is not None or not self._allow_no_value:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000927 value = delimiter + str(value).replace('\n', '\n\t')
928 else:
929 value = ""
930 fp.write("{}{}\n".format(key, value))
931 fp.write("\n")
Eric S. Raymond417c4892000-07-10 18:11:00 +0000932
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000933 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000934 """Remove an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000935 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000936 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000937 else:
938 try:
Fred Drakefce65572002-10-25 18:08:18 +0000939 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000940 except KeyError:
Łukasz Langa949053b2014-09-04 01:36:33 -0700941 raise NoSectionError(section) from None
Fred Drake3c823aa2001-02-26 21:55:34 +0000942 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000943 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000944 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000945 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000946 return existed
947
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000948 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000949 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000950 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000951 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000952 del self._sections[section]
Łukasz Langa49afa382010-11-11 19:53:23 +0000953 del self._proxies[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000954 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000955
Łukasz Langa26d513c2010-11-10 18:57:39 +0000956 def __getitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000957 if key != self.default_section and not self.has_section(key):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000958 raise KeyError(key)
Łukasz Langa49afa382010-11-11 19:53:23 +0000959 return self._proxies[key]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000960
961 def __setitem__(self, key, value):
962 # To conform with the mapping protocol, overwrites existing values in
963 # the section.
964
965 # XXX this is not atomic if read_dict fails at any point. Then again,
966 # no update method in configparser is atomic in this implementation.
Łukasz Langa02101942012-12-31 13:55:11 +0100967 if key == self.default_section:
968 self._defaults.clear()
Łukasz Langaa821f822013-01-01 22:33:19 +0100969 elif key in self._sections:
970 self._sections[key].clear()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000971 self.read_dict({key: value})
972
973 def __delitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000974 if key == self.default_section:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000975 raise ValueError("Cannot remove the default section.")
976 if not self.has_section(key):
977 raise KeyError(key)
978 self.remove_section(key)
979
980 def __contains__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000981 return key == self.default_section or self.has_section(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000982
983 def __len__(self):
984 return len(self._sections) + 1 # the default section
985
986 def __iter__(self):
987 # XXX does it break when underlying container state changed?
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000988 return itertools.chain((self.default_section,), self._sections.keys())
Łukasz Langa26d513c2010-11-10 18:57:39 +0000989
Fred Drakefce65572002-10-25 18:08:18 +0000990 def _read(self, fp, fpname):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000991 """Parse a sectioned configuration file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000992
Fred Drakea4923622010-08-09 12:52:45 +0000993 Each section in a configuration file contains a header, indicated by
994 a name in square brackets (`[]'), plus key/value options, indicated by
Georg Brandl96a60ae2010-07-28 13:13:46 +0000995 `name' and `value' delimited with a specific substring (`=' or `:' by
996 default).
997
Fred Drakea4923622010-08-09 12:52:45 +0000998 Values can span multiple lines, as long as they are indented deeper
999 than the first line of the value. Depending on the parser's mode, blank
1000 lines may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +00001001
1002 Configuration files may include comments, prefixed by specific
Fred Drakea4923622010-08-09 12:52:45 +00001003 characters (`#' and `;' by default). Comments may appear on their own
1004 in an otherwise empty line or may be entered in lines holding values or
Georg Brandl96a60ae2010-07-28 13:13:46 +00001005 section names.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001006 """
Fred Drakea4923622010-08-09 12:52:45 +00001007 elements_added = set()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001008 cursect = None # None, or a dictionary
Fred Drakea4923622010-08-09 12:52:45 +00001009 sectname = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001010 optname = None
1011 lineno = 0
Georg Brandl96a60ae2010-07-28 13:13:46 +00001012 indent_level = 0
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001013 e = None # None, or an exception
Georg Brandl96a60ae2010-07-28 13:13:46 +00001014 for lineno, line in enumerate(fp, start=1):
Łukasz Langacba24322012-07-07 18:54:08 +02001015 comment_start = sys.maxsize
Georg Brandl96a60ae2010-07-28 13:13:46 +00001016 # strip inline comments
Łukasz Langacba24322012-07-07 18:54:08 +02001017 inline_prefixes = {p: -1 for p in self._inline_comment_prefixes}
1018 while comment_start == sys.maxsize and inline_prefixes:
1019 next_prefixes = {}
1020 for prefix, index in inline_prefixes.items():
1021 index = line.find(prefix, index+1)
1022 if index == -1:
1023 continue
1024 next_prefixes[prefix] = index
1025 if index == 0 or (index > 0 and line[index-1].isspace()):
1026 comment_start = min(comment_start, index)
1027 inline_prefixes = next_prefixes
Łukasz Langab25a7912010-12-17 01:32:29 +00001028 # strip full line comments
1029 for prefix in self._comment_prefixes:
1030 if line.strip().startswith(prefix):
1031 comment_start = 0
1032 break
Łukasz Langacba24322012-07-07 18:54:08 +02001033 if comment_start == sys.maxsize:
1034 comment_start = None
Georg Brandl96a60ae2010-07-28 13:13:46 +00001035 value = line[:comment_start].strip()
1036 if not value:
Georg Brandlf206d0e2010-07-29 11:56:20 +00001037 if self._empty_lines_in_values:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001038 # add empty line to the value, but only if there was no
1039 # comment on the line
Georg Brandlf206d0e2010-07-29 11:56:20 +00001040 if (comment_start is None and
1041 cursect is not None and
1042 optname and
1043 cursect[optname] is not None):
1044 cursect[optname].append('') # newlines added at join
Georg Brandl96a60ae2010-07-28 13:13:46 +00001045 else:
1046 # empty line marks end of value
1047 indent_level = sys.maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001048 continue
1049 # continuation line?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001050 first_nonspace = self.NONSPACECRE.search(line)
1051 cur_indent_level = first_nonspace.start() if first_nonspace else 0
1052 if (cursect is not None and optname and
1053 cur_indent_level > indent_level):
1054 cursect[optname].append(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001055 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001056 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001057 indent_level = cur_indent_level
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001058 # is it a section header?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001059 mo = self.SECTCRE.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001060 if mo:
1061 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +00001062 if sectname in self._sections:
Fred Drakea4923622010-08-09 12:52:45 +00001063 if self._strict and sectname in elements_added:
1064 raise DuplicateSectionError(sectname, fpname,
1065 lineno)
Fred Drakefce65572002-10-25 18:08:18 +00001066 cursect = self._sections[sectname]
Fred Drakea4923622010-08-09 12:52:45 +00001067 elements_added.add(sectname)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001068 elif sectname == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001069 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001070 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001071 cursect = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +00001072 self._sections[sectname] = cursect
Łukasz Langa49afa382010-11-11 19:53:23 +00001073 self._proxies[sectname] = SectionProxy(self, sectname)
Fred Drakea4923622010-08-09 12:52:45 +00001074 elements_added.add(sectname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001075 # So sections can't start with a continuation line
1076 optname = None
1077 # no section header in the file?
1078 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001079 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001080 # an option line?
1081 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001082 mo = self._optcre.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001083 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +00001084 optname, vi, optval = mo.group('option', 'vi', 'value')
Georg Brandl96a60ae2010-07-28 13:13:46 +00001085 if not optname:
1086 e = self._handle_error(e, fpname, lineno, line)
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001087 optname = self.optionxform(optname.rstrip())
Fred Drakea4923622010-08-09 12:52:45 +00001088 if (self._strict and
1089 (sectname, optname) in elements_added):
1090 raise DuplicateOptionError(sectname, optname,
1091 fpname, lineno)
1092 elements_added.add((sectname, optname))
Fred Drake03c44a32010-02-19 06:08:41 +00001093 # This check is fine because the OPTCRE cannot
1094 # match if it would set optval to None
1095 if optval is not None:
Fred Drake03c44a32010-02-19 06:08:41 +00001096 optval = optval.strip()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001097 cursect[optname] = [optval]
1098 else:
1099 # valueless option handling
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001100 cursect[optname] = None
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001101 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001102 # a non-fatal parsing error occurred. set up the
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001103 # exception but keep going. the exception will be
1104 # raised at the end of the file and will contain a
1105 # list of all bogus lines
Georg Brandl96a60ae2010-07-28 13:13:46 +00001106 e = self._handle_error(e, fpname, lineno, line)
Łukasz Langa47a9a4b2016-11-26 14:00:39 -08001107 self._join_multiline_values()
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001108 # if any parsing errors occurred, raise an exception
1109 if e:
1110 raise e
Fred Drakefce65572002-10-25 18:08:18 +00001111
Georg Brandl96a60ae2010-07-28 13:13:46 +00001112 def _join_multiline_values(self):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001113 defaults = self.default_section, self._defaults
1114 all_sections = itertools.chain((defaults,),
1115 self._sections.items())
1116 for section, options in all_sections:
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001117 for name, val in options.items():
1118 if isinstance(val, list):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001119 val = '\n'.join(val).rstrip()
1120 options[name] = self._interpolation.before_read(self,
1121 section,
1122 name, val)
Fred Drakefce65572002-10-25 18:08:18 +00001123
Łukasz Langaa5fab172017-08-24 09:43:53 -07001124 def _read_defaults(self, defaults):
1125 """Read the defaults passed in the initializer.
1126 Note: values can be non-string."""
1127 for key, value in defaults.items():
1128 self._defaults[self.optionxform(key)] = value
1129
Georg Brandl96a60ae2010-07-28 13:13:46 +00001130 def _handle_error(self, exc, fpname, lineno, line):
1131 if not exc:
1132 exc = ParsingError(fpname)
1133 exc.append(lineno, repr(line))
1134 return exc
1135
Fred Drakecc645b92010-09-04 04:35:34 +00001136 def _unify_values(self, section, vars):
Raymond Hettingerddb52402011-02-21 19:42:11 +00001137 """Create a sequence of lookups with 'vars' taking priority over
1138 the 'section' which takes priority over the DEFAULTSECT.
1139
Fred Drakefce65572002-10-25 18:08:18 +00001140 """
Raymond Hettingerddb52402011-02-21 19:42:11 +00001141 sectiondict = {}
Fred Drakefce65572002-10-25 18:08:18 +00001142 try:
Raymond Hettingerddb52402011-02-21 19:42:11 +00001143 sectiondict = self._sections[section]
Fred Drakefce65572002-10-25 18:08:18 +00001144 except KeyError:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001145 if section != self.default_section:
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001146 raise NoSectionError(section) from None
Fred Drakefce65572002-10-25 18:08:18 +00001147 # Update with the entry specific variables
Raymond Hettingerddb52402011-02-21 19:42:11 +00001148 vardict = {}
David Goodger68a1abd2004-10-03 15:40:25 +00001149 if vars:
1150 for key, value in vars.items():
Fred Drakecc645b92010-09-04 04:35:34 +00001151 if value is not None:
1152 value = str(value)
Raymond Hettingerddb52402011-02-21 19:42:11 +00001153 vardict[self.optionxform(key)] = value
1154 return _ChainMap(vardict, sectiondict, self._defaults)
Fred Drakecc645b92010-09-04 04:35:34 +00001155
1156 def _convert_to_boolean(self, value):
1157 """Return a boolean value translating from other types if necessary.
1158 """
1159 if value.lower() not in self.BOOLEAN_STATES:
1160 raise ValueError('Not a boolean: %s' % value)
1161 return self.BOOLEAN_STATES[value.lower()]
1162
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001163 def _validate_value_types(self, *, section="", option="", value=""):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001164 """Raises a TypeError for non-string values.
1165
1166 The only legal non-string value if we allow valueless
1167 options is None, so we need to check if the value is a
1168 string if:
1169 - we do not allow valueless options, or
1170 - we allow valueless options but the value is not None
1171
1172 For compatibility reasons this method is not used in classic set()
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001173 for RawConfigParsers. It is invoked in every case for mapping protocol
1174 access and in ConfigParser.set().
Łukasz Langa26d513c2010-11-10 18:57:39 +00001175 """
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001176 if not isinstance(section, str):
1177 raise TypeError("section names must be strings")
1178 if not isinstance(option, str):
1179 raise TypeError("option keys must be strings")
Łukasz Langa26d513c2010-11-10 18:57:39 +00001180 if not self._allow_no_value or value:
1181 if not isinstance(value, str):
1182 raise TypeError("option values must be strings")
1183
Łukasz Langadfdd2f72014-09-15 02:08:41 -07001184 @property
1185 def converters(self):
1186 return self._converters
1187
Łukasz Langa26d513c2010-11-10 18:57:39 +00001188
Fred Drakecc645b92010-09-04 04:35:34 +00001189class ConfigParser(RawConfigParser):
1190 """ConfigParser implementing interpolation."""
1191
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001192 _DEFAULT_INTERPOLATION = BasicInterpolation()
David Goodger1cbf2062004-10-03 15:55:09 +00001193
Fred Drake03c44a32010-02-19 06:08:41 +00001194 def set(self, section, option, value=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001195 """Set an option. Extends RawConfigParser.set by validating type and
1196 interpolation syntax on the value."""
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001197 self._validate_value_types(option=option, value=value)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001198 super().set(section, option, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001199
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001200 def add_section(self, section):
1201 """Create a new section in the configuration. Extends
1202 RawConfigParser.add_section by validating if the section name is
1203 a string."""
1204 self._validate_value_types(section=section)
1205 super().add_section(section)
1206
Łukasz Langaa5fab172017-08-24 09:43:53 -07001207 def _read_defaults(self, defaults):
1208 """Reads the defaults passed in the initializer, implicitly converting
1209 values to strings like the rest of the API."""
1210 self.read_dict({self.default_section: defaults})
1211
Łukasz Langa26d513c2010-11-10 18:57:39 +00001212
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001213class SafeConfigParser(ConfigParser):
1214 """ConfigParser alias for backwards compatibility purposes."""
1215
1216 def __init__(self, *args, **kwargs):
1217 super().__init__(*args, **kwargs)
1218 warnings.warn(
1219 "The SafeConfigParser class has been renamed to ConfigParser "
1220 "in Python 3.2. This alias will be removed in future versions."
1221 " Use ConfigParser directly instead.",
1222 DeprecationWarning, stacklevel=2
1223 )
1224
1225
Łukasz Langa26d513c2010-11-10 18:57:39 +00001226class SectionProxy(MutableMapping):
1227 """A proxy for a single section from a parser."""
1228
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001229 def __init__(self, parser, name):
1230 """Creates a view on a section of the specified `name` in `parser`."""
Łukasz Langa26d513c2010-11-10 18:57:39 +00001231 self._parser = parser
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001232 self._name = name
Łukasz Langadfdd2f72014-09-15 02:08:41 -07001233 for conv in parser.converters:
1234 key = 'get' + conv
1235 getter = functools.partial(self.get, _impl=getattr(parser, key))
1236 setattr(self, key, getter)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001237
1238 def __repr__(self):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001239 return '<Section: {}>'.format(self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001240
1241 def __getitem__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001242 if not self._parser.has_option(self._name, key):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001243 raise KeyError(key)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001244 return self._parser.get(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001245
1246 def __setitem__(self, key, value):
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001247 self._parser._validate_value_types(option=key, value=value)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001248 return self._parser.set(self._name, key, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001249
1250 def __delitem__(self, key):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001251 if not (self._parser.has_option(self._name, key) and
1252 self._parser.remove_option(self._name, key)):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001253 raise KeyError(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001254
1255 def __contains__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001256 return self._parser.has_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001257
1258 def __len__(self):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001259 return len(self._options())
Łukasz Langa26d513c2010-11-10 18:57:39 +00001260
1261 def __iter__(self):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001262 return self._options().__iter__()
1263
1264 def _options(self):
1265 if self._name != self._parser.default_section:
1266 return self._parser.options(self._name)
1267 else:
1268 return self._parser.defaults()
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001269
1270 @property
1271 def parser(self):
1272 # The parser object of the proxy is read-only.
1273 return self._parser
1274
1275 @property
1276 def name(self):
1277 # The name of the section on a proxy is read-only.
1278 return self._name
Łukasz Langadfdd2f72014-09-15 02:08:41 -07001279
1280 def get(self, option, fallback=None, *, raw=False, vars=None,
1281 _impl=None, **kwargs):
1282 """Get an option value.
1283
1284 Unless `fallback` is provided, `None` will be returned if the option
1285 is not found.
1286
1287 """
1288 # If `_impl` is provided, it should be a getter method on the parser
1289 # object that provides the desired type conversion.
1290 if not _impl:
1291 _impl = self._parser.get
1292 return _impl(self._name, option, raw=raw, vars=vars,
1293 fallback=fallback, **kwargs)
1294
1295
1296class ConverterMapping(MutableMapping):
1297 """Enables reuse of get*() methods between the parser and section proxies.
1298
1299 If a parser class implements a getter directly, the value for the given
1300 key will be ``None``. The presence of the converter name here enables
1301 section proxies to find and use the implementation on the parser class.
1302 """
1303
1304 GETTERCRE = re.compile(r"^get(?P<name>.+)$")
1305
1306 def __init__(self, parser):
1307 self._parser = parser
1308 self._data = {}
1309 for getter in dir(self._parser):
1310 m = self.GETTERCRE.match(getter)
1311 if not m or not callable(getattr(self._parser, getter)):
1312 continue
1313 self._data[m.group('name')] = None # See class docstring.
1314
1315 def __getitem__(self, key):
1316 return self._data[key]
1317
1318 def __setitem__(self, key, value):
1319 try:
1320 k = 'get' + key
1321 except TypeError:
1322 raise ValueError('Incompatible key: {} (type: {})'
1323 ''.format(key, type(key)))
1324 if k == 'get':
1325 raise ValueError('Incompatible key: cannot use "" as a name')
1326 self._data[key] = value
1327 func = functools.partial(self._parser._get_conv, conv=value)
1328 func.converter = value
1329 setattr(self._parser, k, func)
1330 for proxy in self._parser.values():
1331 getter = functools.partial(proxy.get, _impl=func)
1332 setattr(proxy, k, getter)
1333
1334 def __delitem__(self, key):
1335 try:
1336 k = 'get' + (key or None)
1337 except TypeError:
1338 raise KeyError(key)
1339 del self._data[key]
1340 for inst in itertools.chain((self._parser,), self._parser.values()):
1341 try:
1342 delattr(inst, k)
1343 except AttributeError:
1344 # don't raise since the entry was present in _data, silently
1345 # clean up
1346 continue
1347
1348 def __iter__(self):
1349 return iter(self._data)
1350
1351 def __len__(self):
1352 return len(self._data)