blob: ecd06600b127ea5d435c18bef6561080f11ccac0 [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
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000146import re
Georg Brandl96a60ae2010-07-28 13:13:46 +0000147import sys
Fred Drakea4923622010-08-09 12:52:45 +0000148import warnings
Guido van Rossum3d209861997-12-09 16:10:31 +0000149
Fred Drakea4923622010-08-09 12:52:45 +0000150__all__ = ["NoSectionError", "DuplicateOptionError", "DuplicateSectionError",
151 "NoOptionError", "InterpolationError", "InterpolationDepthError",
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700152 "InterpolationMissingOptionError", "InterpolationSyntaxError",
153 "ParsingError", "MissingSectionHeaderError",
David Goodger1cbf2062004-10-03 15:55:09 +0000154 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700155 "Interpolation", "BasicInterpolation", "ExtendedInterpolation",
156 "LegacyInterpolation", "SectionProxy", "ConverterMapping",
Fred Drakec2ff9052002-09-27 15:33:11 +0000157 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000158
Guido van Rossum3d209861997-12-09 16:10:31 +0000159DEFAULTSECT = "DEFAULT"
160
Fred Drake2a37f9f2000-09-27 22:43:54 +0000161MAX_INTERPOLATION_DEPTH = 10
162
Guido van Rossum3d209861997-12-09 16:10:31 +0000163
Tim Peters88869f92001-01-14 23:36:06 +0000164
Guido van Rossum3d209861997-12-09 16:10:31 +0000165# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000166class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000167 """Base class for ConfigParser exceptions."""
168
Guido van Rossum3d209861997-12-09 16:10:31 +0000169 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000170 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000171 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000172
Guido van Rossum3d209861997-12-09 16:10:31 +0000173 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000174 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000175
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000176 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000177
Georg Brandl96a60ae2010-07-28 13:13:46 +0000178
Guido van Rossum3d209861997-12-09 16:10:31 +0000179class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000180 """Raised when no section matches a requested option."""
181
Guido van Rossum3d209861997-12-09 16:10:31 +0000182 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000183 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000184 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000185 self.args = (section, )
Guido van Rossum3d209861997-12-09 16:10:31 +0000186
Georg Brandl96a60ae2010-07-28 13:13:46 +0000187
Guido van Rossum3d209861997-12-09 16:10:31 +0000188class DuplicateSectionError(Error):
Fred Drakea4923622010-08-09 12:52:45 +0000189 """Raised when a section is repeated in an input source.
Fred Drake8d5dd982002-12-30 23:51:45 +0000190
Fred Drakea4923622010-08-09 12:52:45 +0000191 Possible repetitions that raise this exception are: multiple creation
192 using the API or in strict parsers when a section is found more than once
193 in a single input file, string or dictionary.
194 """
195
196 def __init__(self, section, source=None, lineno=None):
197 msg = [repr(section), " already exists"]
198 if source is not None:
Łukasz Langaf9b4eb42013-06-23 19:10:25 +0200199 message = ["While reading from ", repr(source)]
Fred Drakea4923622010-08-09 12:52:45 +0000200 if lineno is not None:
201 message.append(" [line {0:2d}]".format(lineno))
202 message.append(": section ")
203 message.extend(msg)
204 msg = message
205 else:
206 msg.insert(0, "Section ")
207 Error.__init__(self, "".join(msg))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000208 self.section = section
Fred Drakea4923622010-08-09 12:52:45 +0000209 self.source = source
210 self.lineno = lineno
211 self.args = (section, source, lineno)
212
213
214class DuplicateOptionError(Error):
215 """Raised by strict parsers when an option is repeated in an input source.
216
217 Current implementation raises this exception only when an option is found
218 more than once in a single file, string or dictionary.
219 """
220
221 def __init__(self, section, option, source=None, lineno=None):
222 msg = [repr(option), " in section ", repr(section),
223 " already exists"]
224 if source is not None:
Łukasz Langaf9b4eb42013-06-23 19:10:25 +0200225 message = ["While reading from ", repr(source)]
Fred Drakea4923622010-08-09 12:52:45 +0000226 if lineno is not None:
227 message.append(" [line {0:2d}]".format(lineno))
228 message.append(": option ")
229 message.extend(msg)
230 msg = message
231 else:
232 msg.insert(0, "Option ")
233 Error.__init__(self, "".join(msg))
234 self.section = section
235 self.option = option
236 self.source = source
237 self.lineno = lineno
238 self.args = (section, option, source, lineno)
Guido van Rossum3d209861997-12-09 16:10:31 +0000239
Georg Brandl96a60ae2010-07-28 13:13:46 +0000240
Guido van Rossum3d209861997-12-09 16:10:31 +0000241class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000242 """A requested option was not found."""
243
Guido van Rossum3d209861997-12-09 16:10:31 +0000244 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000245 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000246 (option, section))
247 self.option = option
248 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000249 self.args = (option, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000250
Georg Brandl96a60ae2010-07-28 13:13:46 +0000251
Guido van Rossum3d209861997-12-09 16:10:31 +0000252class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000253 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000254
Fred Drakee2c64912002-12-31 17:23:27 +0000255 def __init__(self, option, section, msg):
256 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000257 self.option = option
258 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000259 self.args = (option, section, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000260
Georg Brandl96a60ae2010-07-28 13:13:46 +0000261
Fred Drakee2c64912002-12-31 17:23:27 +0000262class InterpolationMissingOptionError(InterpolationError):
263 """A string substitution required a setting which was not available."""
264
265 def __init__(self, option, section, rawval, reference):
266 msg = ("Bad value substitution:\n"
267 "\tsection: [%s]\n"
268 "\toption : %s\n"
269 "\tkey : %s\n"
270 "\trawval : %s\n"
271 % (section, option, reference, rawval))
272 InterpolationError.__init__(self, option, section, msg)
273 self.reference = reference
Michael Foordbd6c0792010-07-25 23:09:25 +0000274 self.args = (option, section, rawval, reference)
Fred Drakee2c64912002-12-31 17:23:27 +0000275
Georg Brandl96a60ae2010-07-28 13:13:46 +0000276
Fred Drakee2c64912002-12-31 17:23:27 +0000277class InterpolationSyntaxError(InterpolationError):
Fred Drakea4923622010-08-09 12:52:45 +0000278 """Raised when the source text contains invalid syntax.
279
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000280 Current implementation raises this exception when the source text into
281 which substitutions are made does not conform to the required syntax.
Fred Drakea4923622010-08-09 12:52:45 +0000282 """
Neal Norwitzce1d9442002-12-30 23:38:47 +0000283
Georg Brandl96a60ae2010-07-28 13:13:46 +0000284
Fred Drakee2c64912002-12-31 17:23:27 +0000285class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000286 """Raised when substitutions are nested too deeply."""
287
Fred Drake2a37f9f2000-09-27 22:43:54 +0000288 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000289 msg = ("Value interpolation too deeply recursive:\n"
290 "\tsection: [%s]\n"
291 "\toption : %s\n"
292 "\trawval : %s\n"
293 % (section, option, rawval))
294 InterpolationError.__init__(self, option, section, msg)
Michael Foordbd6c0792010-07-25 23:09:25 +0000295 self.args = (option, section, rawval)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000296
Georg Brandl96a60ae2010-07-28 13:13:46 +0000297
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000298class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000299 """Raised when a configuration file does not follow legal syntax."""
300
Fred Drakea4923622010-08-09 12:52:45 +0000301 def __init__(self, source=None, filename=None):
302 # Exactly one of `source'/`filename' arguments has to be given.
303 # `filename' kept for compatibility.
304 if filename and source:
305 raise ValueError("Cannot specify both `filename' and `source'. "
306 "Use `source'.")
307 elif not filename and not source:
308 raise ValueError("Required argument `source' not given.")
309 elif filename:
310 source = filename
Serhiy Storchakabc27a052014-02-06 22:49:45 +0200311 Error.__init__(self, 'Source contains parsing errors: %r' % source)
Fred Drakea4923622010-08-09 12:52:45 +0000312 self.source = source
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000313 self.errors = []
Fred Drakea4923622010-08-09 12:52:45 +0000314 self.args = (source, )
315
316 @property
317 def filename(self):
318 """Deprecated, use `source'."""
319 warnings.warn(
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000320 "The 'filename' attribute will be removed in future versions. "
Fred Drakea4923622010-08-09 12:52:45 +0000321 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000322 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000323 )
324 return self.source
325
326 @filename.setter
327 def filename(self, value):
328 """Deprecated, user `source'."""
329 warnings.warn(
330 "The 'filename' attribute will be removed in future versions. "
331 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000332 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000333 )
334 self.source = value
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000335
336 def append(self, lineno, line):
337 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000338 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000339
Georg Brandl96a60ae2010-07-28 13:13:46 +0000340
Fred Drake2a37f9f2000-09-27 22:43:54 +0000341class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000342 """Raised when a key-value pair is found before any section header."""
343
Fred Drake2a37f9f2000-09-27 22:43:54 +0000344 def __init__(self, filename, lineno, line):
345 Error.__init__(
346 self,
Serhiy Storchakabc27a052014-02-06 22:49:45 +0200347 'File contains no section headers.\nfile: %r, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000348 (filename, lineno, line))
Fred Drakea4923622010-08-09 12:52:45 +0000349 self.source = filename
Fred Drake2a37f9f2000-09-27 22:43:54 +0000350 self.lineno = lineno
351 self.line = line
Michael Foordbd6c0792010-07-25 23:09:25 +0000352 self.args = (filename, lineno, line)
Guido van Rossum3d209861997-12-09 16:10:31 +0000353
Georg Brandl96a60ae2010-07-28 13:13:46 +0000354
Fred Drakecc645b92010-09-04 04:35:34 +0000355# Used in parser getters to indicate the default behaviour when a specific
356# option is not found it to raise an exception. Created to enable `None' as
357# a valid fallback value.
358_UNSET = object()
359
360
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000361class Interpolation:
362 """Dummy interpolation that passes the value through with no changes."""
363
364 def before_get(self, parser, section, option, value, defaults):
365 return value
366
367 def before_set(self, parser, section, option, value):
368 return value
369
370 def before_read(self, parser, section, option, value):
371 return value
372
373 def before_write(self, parser, section, option, value):
374 return value
375
376
377class BasicInterpolation(Interpolation):
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000378 """Interpolation as implemented in the classic ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000379
380 The option values can contain format strings which refer to other values in
381 the same section, or values in the special default section.
382
383 For example:
384
385 something: %(dir)s/whatever
386
387 would resolve the "%(dir)s" to the value of dir. All reference
388 expansions are done late, on demand. If a user needs to use a bare % in
Ezio Melottie130a522011-10-19 10:58:56 +0300389 a configuration file, she can escape it by writing %%. Other % usage
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000390 is considered a user error and raises `InterpolationSyntaxError'."""
391
392 _KEYCRE = re.compile(r"%\(([^)]+)\)s")
393
394 def before_get(self, parser, section, option, value, defaults):
395 L = []
396 self._interpolate_some(parser, option, L, value, section, defaults, 1)
397 return ''.join(L)
398
399 def before_set(self, parser, section, option, value):
400 tmp_value = value.replace('%%', '') # escaped percent signs
401 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
402 if '%' in tmp_value:
403 raise ValueError("invalid interpolation syntax in %r at "
404 "position %d" % (value, tmp_value.find('%')))
405 return value
406
407 def _interpolate_some(self, parser, option, accum, rest, section, map,
408 depth):
409 if depth > MAX_INTERPOLATION_DEPTH:
410 raise InterpolationDepthError(option, section, rest)
411 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(
Łukasz Langa949053b2014-09-04 01:36:33 -0700435 option, section, rest, 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):
469 if depth > MAX_INTERPOLATION_DEPTH:
470 raise InterpolationDepthError(option, section, rest)
471 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(
Łukasz Langa949053b2014-09-04 01:36:33 -0700507 option, section, rest, ":".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)
David Goodger68a1abd2004-10-03 15:40:25 +0000613 if defaults:
614 for key, value in defaults.items():
615 self._defaults[self.optionxform(key)] = value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000616 self._delimiters = tuple(delimiters)
617 if delimiters == ('=', ':'):
618 self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
619 else:
Fred Drakea4923622010-08-09 12:52:45 +0000620 d = "|".join(re.escape(d) for d in delimiters)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000621 if allow_no_value:
Fred Drakea4923622010-08-09 12:52:45 +0000622 self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000623 re.VERBOSE)
624 else:
Fred Drakea4923622010-08-09 12:52:45 +0000625 self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000626 re.VERBOSE)
Łukasz Langab25a7912010-12-17 01:32:29 +0000627 self._comment_prefixes = tuple(comment_prefixes or ())
628 self._inline_comment_prefixes = tuple(inline_comment_prefixes or ())
Fred Drakea4923622010-08-09 12:52:45 +0000629 self._strict = strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000630 self._allow_no_value = allow_no_value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000631 self._empty_lines_in_values = empty_lines_in_values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000632 self.default_section=default_section
Łukasz Langa1aa422f2011-04-28 17:03:45 +0200633 self._interpolation = interpolation
634 if self._interpolation is _UNSET:
635 self._interpolation = self._DEFAULT_INTERPOLATION
636 if self._interpolation is None:
637 self._interpolation = Interpolation()
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700638 if converters is not _UNSET:
639 self._converters.update(converters)
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):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000680 """Read and parse a filename or a list 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
Barry Warsaw25394511999-10-12 16:12:48 +0000683 designed so that you can specify a list 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
686 configuration files in the list will be read. A single
687 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 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000691 if isinstance(filenames, str):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000692 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000693 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000694 for filename in filenames:
695 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000696 with open(filename, encoding=encoding) as fp:
697 self._read(fp, filename)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200698 except OSError:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000699 continue
Fred Drake82903142004-05-18 04:24:02 +0000700 read_ok.append(filename)
701 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000702
Fred Drakea4923622010-08-09 12:52:45 +0000703 def read_file(self, f, source=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000704 """Like read() but the argument must be a file-like object.
705
Łukasz Langadaab1c82011-04-27 18:10:05 +0200706 The `f' argument must be iterable, returning one line at a time.
707 Optional second argument is the `source' specifying the name of the
708 file being read. If not given, it is taken from f.name. If `f' has no
709 `name' attribute, `<???>' is used.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000710 """
Fred Drakea4923622010-08-09 12:52:45 +0000711 if source is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000712 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000713 source = f.name
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000714 except AttributeError:
Fred Drakea4923622010-08-09 12:52:45 +0000715 source = '<???>'
716 self._read(f, source)
717
718 def read_string(self, string, source='<string>'):
719 """Read configuration from a given string."""
720 sfile = io.StringIO(string)
721 self.read_file(sfile, source)
722
723 def read_dict(self, dictionary, source='<dict>'):
724 """Read configuration from a dictionary.
725
726 Keys are section names, values are dictionaries with keys and values
727 that should be present in the section. If the used dictionary type
728 preserves order, sections and their keys will be added in order.
729
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000730 All types held in the dictionary are converted to strings during
731 reading, including section names, option names and keys.
732
Fred Drakea4923622010-08-09 12:52:45 +0000733 Optional second argument is the `source' specifying the name of the
734 dictionary being read.
735 """
736 elements_added = set()
737 for section, keys in dictionary.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000738 section = str(section)
Fred Drakea4923622010-08-09 12:52:45 +0000739 try:
740 self.add_section(section)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000741 except (DuplicateSectionError, ValueError):
Fred Drakea4923622010-08-09 12:52:45 +0000742 if self._strict and section in elements_added:
743 raise
Łukasz Langa71b37a52010-12-17 21:56:32 +0000744 elements_added.add(section)
Fred Drakea4923622010-08-09 12:52:45 +0000745 for key, value in keys.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000746 key = self.optionxform(str(key))
Fred Drakecc645b92010-09-04 04:35:34 +0000747 if value is not None:
748 value = str(value)
Fred Drakea4923622010-08-09 12:52:45 +0000749 if self._strict and (section, key) in elements_added:
750 raise DuplicateOptionError(section, key, source)
751 elements_added.add((section, key))
752 self.set(section, key, value)
753
754 def readfp(self, fp, filename=None):
755 """Deprecated, use read_file instead."""
756 warnings.warn(
757 "This method will be removed in future versions. "
758 "Use 'parser.read_file()' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000759 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000760 )
761 self.read_file(fp, source=filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000762
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000763 def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000764 """Get an option value for a given section.
765
766 If `vars' is provided, it must be a dictionary. The option is looked up
767 in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000768 If the key is not found and `fallback' is provided, it is used as
769 a fallback value. `None' can be provided as a `fallback' value.
770
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000771 If interpolation is enabled and the optional argument `raw' is False,
772 all interpolations are expanded in the return values.
773
774 Arguments `raw', `vars', and `fallback' are keyword only.
775
776 The section DEFAULT is special.
Fred Drakecc645b92010-09-04 04:35:34 +0000777 """
778 try:
779 d = self._unify_values(section, vars)
780 except NoSectionError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000781 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000782 raise
Fred Drakefce65572002-10-25 18:08:18 +0000783 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000784 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000785 option = self.optionxform(option)
786 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000787 value = d[option]
Fred Drakecc645b92010-09-04 04:35:34 +0000788 except KeyError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000789 if fallback is _UNSET:
Fred Drakefce65572002-10-25 18:08:18 +0000790 raise NoOptionError(option, section)
Fred Drakecc645b92010-09-04 04:35:34 +0000791 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000792 return fallback
Fred Drake2a37f9f2000-09-27 22:43:54 +0000793
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000794 if raw or value is None:
795 return value
796 else:
797 return self._interpolation.before_get(self, section, option, value,
798 d)
Fred Drake2ca041f2002-09-27 15:49:56 +0000799
Łukasz Langa26d513c2010-11-10 18:57:39 +0000800 def _get(self, section, conv, option, **kwargs):
801 return conv(self.get(section, option, **kwargs))
Guido van Rossum3d209861997-12-09 16:10:31 +0000802
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700803 def _get_conv(self, section, option, conv, *, raw=False, vars=None,
804 fallback=_UNSET, **kwargs):
Fred Drakecc645b92010-09-04 04:35:34 +0000805 try:
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700806 return self._get(section, conv, option, raw=raw, vars=vars,
807 **kwargs)
Fred Drakecc645b92010-09-04 04:35:34 +0000808 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000809 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000810 raise
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700811 return fallback
812
813 # getint, getfloat and getboolean provided directly for backwards compat
814 def getint(self, section, option, *, raw=False, vars=None,
815 fallback=_UNSET, **kwargs):
816 return self._get_conv(section, option, int, raw=raw, vars=vars,
817 fallback=fallback, **kwargs)
Guido van Rossum3d209861997-12-09 16:10:31 +0000818
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000819 def getfloat(self, section, option, *, raw=False, vars=None,
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700820 fallback=_UNSET, **kwargs):
821 return self._get_conv(section, option, float, raw=raw, vars=vars,
822 fallback=fallback, **kwargs)
Guido van Rossum3d209861997-12-09 16:10:31 +0000823
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000824 def getboolean(self, section, option, *, raw=False, vars=None,
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700825 fallback=_UNSET, **kwargs):
826 return self._get_conv(section, option, self._convert_to_boolean,
827 raw=raw, vars=vars, fallback=fallback, **kwargs)
Guido van Rossum3d209861997-12-09 16:10:31 +0000828
Łukasz Langa71b37a52010-12-17 21:56:32 +0000829 def items(self, section=_UNSET, raw=False, vars=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000830 """Return a list of (name, value) tuples for each option in a section.
831
832 All % interpolations are expanded in the return values, based on the
833 defaults passed into the constructor, unless the optional argument
834 `raw' is true. Additional substitutions may be provided using the
835 `vars' argument, which must be a dictionary whose contents overrides
836 any pre-existing defaults.
837
838 The section DEFAULT is special.
839 """
Łukasz Langa71b37a52010-12-17 21:56:32 +0000840 if section is _UNSET:
841 return super().items()
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000842 d = self._defaults.copy()
843 try:
844 d.update(self._sections[section])
845 except KeyError:
846 if section != self.default_section:
847 raise NoSectionError(section)
848 # Update with the entry specific variables
849 if vars:
850 for key, value in vars.items():
851 d[self.optionxform(key)] = value
Łukasz Langa24bcc612010-12-04 11:48:11 +0000852 value_getter = lambda option: self._interpolation.before_get(self,
853 section, option, d[option], d)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000854 if raw:
Łukasz Langa24bcc612010-12-04 11:48:11 +0000855 value_getter = lambda option: d[option]
856 return [(option, value_getter(option)) for option in d.keys()]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000857
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100858 def popitem(self):
859 """Remove a section from the parser and return it as
860 a (section_name, section_proxy) tuple. If no section is present, raise
861 KeyError.
862
863 The section DEFAULT is never returned because it cannot be removed.
864 """
865 for key in self.sections():
866 value = self[key]
867 del self[key]
868 return key, value
869 raise KeyError
870
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000871 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000872 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000873
Eric S. Raymond417c4892000-07-10 18:11:00 +0000874 def has_option(self, section, option):
Łukasz Langa71b37a52010-12-17 21:56:32 +0000875 """Check for the existence of a given option in a given section.
876 If the specified `section' is None or an empty string, DEFAULT is
877 assumed. If the specified `section' does not exist, returns False."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000878 if not section or section == self.default_section:
Fred Drakec2ff9052002-09-27 15:33:11 +0000879 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000880 return option in self._defaults
881 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000882 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000883 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000884 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000885 return (option in self._sections[section]
886 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000887
Fred Drake03c44a32010-02-19 06:08:41 +0000888 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000889 """Set an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000890 if value:
891 value = self._interpolation.before_set(self, section, option,
892 value)
893 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000894 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000895 else:
896 try:
Fred Drakefce65572002-10-25 18:08:18 +0000897 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000898 except KeyError:
Łukasz Langa949053b2014-09-04 01:36:33 -0700899 raise NoSectionError(section) from None
Fred Drakec2ff9052002-09-27 15:33:11 +0000900 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000901
Georg Brandl96a60ae2010-07-28 13:13:46 +0000902 def write(self, fp, space_around_delimiters=True):
903 """Write an .ini-format representation of the configuration state.
904
905 If `space_around_delimiters' is True (the default), delimiters
906 between keys and values are surrounded by spaces.
907 """
908 if space_around_delimiters:
909 d = " {} ".format(self._delimiters[0])
910 else:
911 d = self._delimiters[0]
Fred Drakefce65572002-10-25 18:08:18 +0000912 if self._defaults:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000913 self._write_section(fp, self.default_section,
Łukasz Langac264c092010-11-20 16:15:37 +0000914 self._defaults.items(), d)
Fred Drakefce65572002-10-25 18:08:18 +0000915 for section in self._sections:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000916 self._write_section(fp, section,
917 self._sections[section].items(), d)
918
919 def _write_section(self, fp, section_name, section_items, delimiter):
920 """Write a single section to the specified `fp'."""
921 fp.write("[{}]\n".format(section_name))
922 for key, value in section_items:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000923 value = self._interpolation.before_write(self, section_name, key,
924 value)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000925 if value is not None or not self._allow_no_value:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000926 value = delimiter + str(value).replace('\n', '\n\t')
927 else:
928 value = ""
929 fp.write("{}{}\n".format(key, value))
930 fp.write("\n")
Eric S. Raymond417c4892000-07-10 18:11:00 +0000931
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000932 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000933 """Remove an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000934 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000935 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000936 else:
937 try:
Fred Drakefce65572002-10-25 18:08:18 +0000938 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000939 except KeyError:
Łukasz Langa949053b2014-09-04 01:36:33 -0700940 raise NoSectionError(section) from None
Fred Drake3c823aa2001-02-26 21:55:34 +0000941 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000942 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000943 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000944 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000945 return existed
946
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000947 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000948 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000949 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000950 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000951 del self._sections[section]
Łukasz Langa49afa382010-11-11 19:53:23 +0000952 del self._proxies[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000953 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000954
Łukasz Langa26d513c2010-11-10 18:57:39 +0000955 def __getitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000956 if key != self.default_section and not self.has_section(key):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000957 raise KeyError(key)
Łukasz Langa49afa382010-11-11 19:53:23 +0000958 return self._proxies[key]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000959
960 def __setitem__(self, key, value):
961 # To conform with the mapping protocol, overwrites existing values in
962 # the section.
963
964 # XXX this is not atomic if read_dict fails at any point. Then again,
965 # no update method in configparser is atomic in this implementation.
Łukasz Langa02101942012-12-31 13:55:11 +0100966 if key == self.default_section:
967 self._defaults.clear()
Łukasz Langaa821f822013-01-01 22:33:19 +0100968 elif key in self._sections:
969 self._sections[key].clear()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000970 self.read_dict({key: value})
971
972 def __delitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000973 if key == self.default_section:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000974 raise ValueError("Cannot remove the default section.")
975 if not self.has_section(key):
976 raise KeyError(key)
977 self.remove_section(key)
978
979 def __contains__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000980 return key == self.default_section or self.has_section(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000981
982 def __len__(self):
983 return len(self._sections) + 1 # the default section
984
985 def __iter__(self):
986 # XXX does it break when underlying container state changed?
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000987 return itertools.chain((self.default_section,), self._sections.keys())
Łukasz Langa26d513c2010-11-10 18:57:39 +0000988
Fred Drakefce65572002-10-25 18:08:18 +0000989 def _read(self, fp, fpname):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000990 """Parse a sectioned configuration file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000991
Fred Drakea4923622010-08-09 12:52:45 +0000992 Each section in a configuration file contains a header, indicated by
993 a name in square brackets (`[]'), plus key/value options, indicated by
Georg Brandl96a60ae2010-07-28 13:13:46 +0000994 `name' and `value' delimited with a specific substring (`=' or `:' by
995 default).
996
Fred Drakea4923622010-08-09 12:52:45 +0000997 Values can span multiple lines, as long as they are indented deeper
998 than the first line of the value. Depending on the parser's mode, blank
999 lines may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +00001000
1001 Configuration files may include comments, prefixed by specific
Fred Drakea4923622010-08-09 12:52:45 +00001002 characters (`#' and `;' by default). Comments may appear on their own
1003 in an otherwise empty line or may be entered in lines holding values or
Georg Brandl96a60ae2010-07-28 13:13:46 +00001004 section names.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001005 """
Fred Drakea4923622010-08-09 12:52:45 +00001006 elements_added = set()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001007 cursect = None # None, or a dictionary
Fred Drakea4923622010-08-09 12:52:45 +00001008 sectname = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001009 optname = None
1010 lineno = 0
Georg Brandl96a60ae2010-07-28 13:13:46 +00001011 indent_level = 0
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001012 e = None # None, or an exception
Georg Brandl96a60ae2010-07-28 13:13:46 +00001013 for lineno, line in enumerate(fp, start=1):
Łukasz Langacba24322012-07-07 18:54:08 +02001014 comment_start = sys.maxsize
Georg Brandl96a60ae2010-07-28 13:13:46 +00001015 # strip inline comments
Łukasz Langacba24322012-07-07 18:54:08 +02001016 inline_prefixes = {p: -1 for p in self._inline_comment_prefixes}
1017 while comment_start == sys.maxsize and inline_prefixes:
1018 next_prefixes = {}
1019 for prefix, index in inline_prefixes.items():
1020 index = line.find(prefix, index+1)
1021 if index == -1:
1022 continue
1023 next_prefixes[prefix] = index
1024 if index == 0 or (index > 0 and line[index-1].isspace()):
1025 comment_start = min(comment_start, index)
1026 inline_prefixes = next_prefixes
Łukasz Langab25a7912010-12-17 01:32:29 +00001027 # strip full line comments
1028 for prefix in self._comment_prefixes:
1029 if line.strip().startswith(prefix):
1030 comment_start = 0
1031 break
Łukasz Langacba24322012-07-07 18:54:08 +02001032 if comment_start == sys.maxsize:
1033 comment_start = None
Georg Brandl96a60ae2010-07-28 13:13:46 +00001034 value = line[:comment_start].strip()
1035 if not value:
Georg Brandlf206d0e2010-07-29 11:56:20 +00001036 if self._empty_lines_in_values:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001037 # add empty line to the value, but only if there was no
1038 # comment on the line
Georg Brandlf206d0e2010-07-29 11:56:20 +00001039 if (comment_start is None and
1040 cursect is not None and
1041 optname and
1042 cursect[optname] is not None):
1043 cursect[optname].append('') # newlines added at join
Georg Brandl96a60ae2010-07-28 13:13:46 +00001044 else:
1045 # empty line marks end of value
1046 indent_level = sys.maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001047 continue
1048 # continuation line?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001049 first_nonspace = self.NONSPACECRE.search(line)
1050 cur_indent_level = first_nonspace.start() if first_nonspace else 0
1051 if (cursect is not None and optname and
1052 cur_indent_level > indent_level):
1053 cursect[optname].append(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001054 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001055 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001056 indent_level = cur_indent_level
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001057 # is it a section header?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001058 mo = self.SECTCRE.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001059 if mo:
1060 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +00001061 if sectname in self._sections:
Fred Drakea4923622010-08-09 12:52:45 +00001062 if self._strict and sectname in elements_added:
1063 raise DuplicateSectionError(sectname, fpname,
1064 lineno)
Fred Drakefce65572002-10-25 18:08:18 +00001065 cursect = self._sections[sectname]
Fred Drakea4923622010-08-09 12:52:45 +00001066 elements_added.add(sectname)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001067 elif sectname == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001068 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001069 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001070 cursect = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +00001071 self._sections[sectname] = cursect
Łukasz Langa49afa382010-11-11 19:53:23 +00001072 self._proxies[sectname] = SectionProxy(self, sectname)
Fred Drakea4923622010-08-09 12:52:45 +00001073 elements_added.add(sectname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001074 # So sections can't start with a continuation line
1075 optname = None
1076 # no section header in the file?
1077 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001078 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001079 # an option line?
1080 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001081 mo = self._optcre.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001082 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +00001083 optname, vi, optval = mo.group('option', 'vi', 'value')
Georg Brandl96a60ae2010-07-28 13:13:46 +00001084 if not optname:
1085 e = self._handle_error(e, fpname, lineno, line)
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001086 optname = self.optionxform(optname.rstrip())
Fred Drakea4923622010-08-09 12:52:45 +00001087 if (self._strict and
1088 (sectname, optname) in elements_added):
1089 raise DuplicateOptionError(sectname, optname,
1090 fpname, lineno)
1091 elements_added.add((sectname, optname))
Fred Drake03c44a32010-02-19 06:08:41 +00001092 # This check is fine because the OPTCRE cannot
1093 # match if it would set optval to None
1094 if optval is not None:
Fred Drake03c44a32010-02-19 06:08:41 +00001095 optval = optval.strip()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001096 cursect[optname] = [optval]
1097 else:
1098 # valueless option handling
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001099 cursect[optname] = None
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001100 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001101 # a non-fatal parsing error occurred. set up the
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001102 # exception but keep going. the exception will be
1103 # raised at the end of the file and will contain a
1104 # list of all bogus lines
Georg Brandl96a60ae2010-07-28 13:13:46 +00001105 e = self._handle_error(e, fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001106 # if any parsing errors occurred, raise an exception
1107 if e:
1108 raise e
Georg Brandl96a60ae2010-07-28 13:13:46 +00001109 self._join_multiline_values()
Fred Drakefce65572002-10-25 18:08:18 +00001110
Georg Brandl96a60ae2010-07-28 13:13:46 +00001111 def _join_multiline_values(self):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001112 defaults = self.default_section, self._defaults
1113 all_sections = itertools.chain((defaults,),
1114 self._sections.items())
1115 for section, options in all_sections:
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001116 for name, val in options.items():
1117 if isinstance(val, list):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001118 val = '\n'.join(val).rstrip()
1119 options[name] = self._interpolation.before_read(self,
1120 section,
1121 name, val)
Fred Drakefce65572002-10-25 18:08:18 +00001122
Georg Brandl96a60ae2010-07-28 13:13:46 +00001123 def _handle_error(self, exc, fpname, lineno, line):
1124 if not exc:
1125 exc = ParsingError(fpname)
1126 exc.append(lineno, repr(line))
1127 return exc
1128
Fred Drakecc645b92010-09-04 04:35:34 +00001129 def _unify_values(self, section, vars):
Raymond Hettingerddb52402011-02-21 19:42:11 +00001130 """Create a sequence of lookups with 'vars' taking priority over
1131 the 'section' which takes priority over the DEFAULTSECT.
1132
Fred Drakefce65572002-10-25 18:08:18 +00001133 """
Raymond Hettingerddb52402011-02-21 19:42:11 +00001134 sectiondict = {}
Fred Drakefce65572002-10-25 18:08:18 +00001135 try:
Raymond Hettingerddb52402011-02-21 19:42:11 +00001136 sectiondict = self._sections[section]
Fred Drakefce65572002-10-25 18:08:18 +00001137 except KeyError:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001138 if section != self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001139 raise NoSectionError(section)
1140 # Update with the entry specific variables
Raymond Hettingerddb52402011-02-21 19:42:11 +00001141 vardict = {}
David Goodger68a1abd2004-10-03 15:40:25 +00001142 if vars:
1143 for key, value in vars.items():
Fred Drakecc645b92010-09-04 04:35:34 +00001144 if value is not None:
1145 value = str(value)
Raymond Hettingerddb52402011-02-21 19:42:11 +00001146 vardict[self.optionxform(key)] = value
1147 return _ChainMap(vardict, sectiondict, self._defaults)
Fred Drakecc645b92010-09-04 04:35:34 +00001148
1149 def _convert_to_boolean(self, value):
1150 """Return a boolean value translating from other types if necessary.
1151 """
1152 if value.lower() not in self.BOOLEAN_STATES:
1153 raise ValueError('Not a boolean: %s' % value)
1154 return self.BOOLEAN_STATES[value.lower()]
1155
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001156 def _validate_value_types(self, *, section="", option="", value=""):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001157 """Raises a TypeError for non-string values.
1158
1159 The only legal non-string value if we allow valueless
1160 options is None, so we need to check if the value is a
1161 string if:
1162 - we do not allow valueless options, or
1163 - we allow valueless options but the value is not None
1164
1165 For compatibility reasons this method is not used in classic set()
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001166 for RawConfigParsers. It is invoked in every case for mapping protocol
1167 access and in ConfigParser.set().
Łukasz Langa26d513c2010-11-10 18:57:39 +00001168 """
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001169 if not isinstance(section, str):
1170 raise TypeError("section names must be strings")
1171 if not isinstance(option, str):
1172 raise TypeError("option keys must be strings")
Łukasz Langa26d513c2010-11-10 18:57:39 +00001173 if not self._allow_no_value or value:
1174 if not isinstance(value, str):
1175 raise TypeError("option values must be strings")
1176
Łukasz Langadfdd2f72014-09-15 02:08:41 -07001177 @property
1178 def converters(self):
1179 return self._converters
1180
Łukasz Langa26d513c2010-11-10 18:57:39 +00001181
Fred Drakecc645b92010-09-04 04:35:34 +00001182class ConfigParser(RawConfigParser):
1183 """ConfigParser implementing interpolation."""
1184
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001185 _DEFAULT_INTERPOLATION = BasicInterpolation()
David Goodger1cbf2062004-10-03 15:55:09 +00001186
Fred Drake03c44a32010-02-19 06:08:41 +00001187 def set(self, section, option, value=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001188 """Set an option. Extends RawConfigParser.set by validating type and
1189 interpolation syntax on the value."""
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001190 self._validate_value_types(option=option, value=value)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001191 super().set(section, option, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001192
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001193 def add_section(self, section):
1194 """Create a new section in the configuration. Extends
1195 RawConfigParser.add_section by validating if the section name is
1196 a string."""
1197 self._validate_value_types(section=section)
1198 super().add_section(section)
1199
Łukasz Langa26d513c2010-11-10 18:57:39 +00001200
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001201class SafeConfigParser(ConfigParser):
1202 """ConfigParser alias for backwards compatibility purposes."""
1203
1204 def __init__(self, *args, **kwargs):
1205 super().__init__(*args, **kwargs)
1206 warnings.warn(
1207 "The SafeConfigParser class has been renamed to ConfigParser "
1208 "in Python 3.2. This alias will be removed in future versions."
1209 " Use ConfigParser directly instead.",
1210 DeprecationWarning, stacklevel=2
1211 )
1212
1213
Łukasz Langa26d513c2010-11-10 18:57:39 +00001214class SectionProxy(MutableMapping):
1215 """A proxy for a single section from a parser."""
1216
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001217 def __init__(self, parser, name):
1218 """Creates a view on a section of the specified `name` in `parser`."""
Łukasz Langa26d513c2010-11-10 18:57:39 +00001219 self._parser = parser
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001220 self._name = name
Łukasz Langadfdd2f72014-09-15 02:08:41 -07001221 for conv in parser.converters:
1222 key = 'get' + conv
1223 getter = functools.partial(self.get, _impl=getattr(parser, key))
1224 setattr(self, key, getter)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001225
1226 def __repr__(self):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001227 return '<Section: {}>'.format(self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001228
1229 def __getitem__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001230 if not self._parser.has_option(self._name, key):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001231 raise KeyError(key)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001232 return self._parser.get(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001233
1234 def __setitem__(self, key, value):
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001235 self._parser._validate_value_types(option=key, value=value)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001236 return self._parser.set(self._name, key, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001237
1238 def __delitem__(self, key):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001239 if not (self._parser.has_option(self._name, key) and
1240 self._parser.remove_option(self._name, key)):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001241 raise KeyError(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001242
1243 def __contains__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001244 return self._parser.has_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001245
1246 def __len__(self):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001247 return len(self._options())
Łukasz Langa26d513c2010-11-10 18:57:39 +00001248
1249 def __iter__(self):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001250 return self._options().__iter__()
1251
1252 def _options(self):
1253 if self._name != self._parser.default_section:
1254 return self._parser.options(self._name)
1255 else:
1256 return self._parser.defaults()
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001257
1258 @property
1259 def parser(self):
1260 # The parser object of the proxy is read-only.
1261 return self._parser
1262
1263 @property
1264 def name(self):
1265 # The name of the section on a proxy is read-only.
1266 return self._name
Łukasz Langadfdd2f72014-09-15 02:08:41 -07001267
1268 def get(self, option, fallback=None, *, raw=False, vars=None,
1269 _impl=None, **kwargs):
1270 """Get an option value.
1271
1272 Unless `fallback` is provided, `None` will be returned if the option
1273 is not found.
1274
1275 """
1276 # If `_impl` is provided, it should be a getter method on the parser
1277 # object that provides the desired type conversion.
1278 if not _impl:
1279 _impl = self._parser.get
1280 return _impl(self._name, option, raw=raw, vars=vars,
1281 fallback=fallback, **kwargs)
1282
1283
1284class ConverterMapping(MutableMapping):
1285 """Enables reuse of get*() methods between the parser and section proxies.
1286
1287 If a parser class implements a getter directly, the value for the given
1288 key will be ``None``. The presence of the converter name here enables
1289 section proxies to find and use the implementation on the parser class.
1290 """
1291
1292 GETTERCRE = re.compile(r"^get(?P<name>.+)$")
1293
1294 def __init__(self, parser):
1295 self._parser = parser
1296 self._data = {}
1297 for getter in dir(self._parser):
1298 m = self.GETTERCRE.match(getter)
1299 if not m or not callable(getattr(self._parser, getter)):
1300 continue
1301 self._data[m.group('name')] = None # See class docstring.
1302
1303 def __getitem__(self, key):
1304 return self._data[key]
1305
1306 def __setitem__(self, key, value):
1307 try:
1308 k = 'get' + key
1309 except TypeError:
1310 raise ValueError('Incompatible key: {} (type: {})'
1311 ''.format(key, type(key)))
1312 if k == 'get':
1313 raise ValueError('Incompatible key: cannot use "" as a name')
1314 self._data[key] = value
1315 func = functools.partial(self._parser._get_conv, conv=value)
1316 func.converter = value
1317 setattr(self._parser, k, func)
1318 for proxy in self._parser.values():
1319 getter = functools.partial(proxy.get, _impl=func)
1320 setattr(proxy, k, getter)
1321
1322 def __delitem__(self, key):
1323 try:
1324 k = 'get' + (key or None)
1325 except TypeError:
1326 raise KeyError(key)
1327 del self._data[key]
1328 for inst in itertools.chain((self._parser,), self._parser.values()):
1329 try:
1330 delattr(inst, k)
1331 except AttributeError:
1332 # don't raise since the entry was present in _data, silently
1333 # clean up
1334 continue
1335
1336 def __iter__(self):
1337 return iter(self._data)
1338
1339 def __len__(self):
1340 return len(self._data)