blob: dcb7ec4df28effd41a0feed1483e3176e8258f91 [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,
20 empty_lines_in_values=True):
Georg Brandl96a60ae2010-07-28 13:13:46 +000021 Create the parser. When `defaults' is given, it is initialized into the
22 dictionary or intrinsic defaults. The keys must be strings, the values
Łukasz Langa5c863392010-11-21 13:41:35 +000023 must be appropriate for %()s string interpolation.
Georg Brandl96a60ae2010-07-28 13:13:46 +000024
25 When `dict_type' is given, it will be used to create the dictionary
26 objects for the list of sections, for the options within a section, and
27 for the default values.
28
29 When `delimiters' is given, it will be used as the set of substrings
30 that divide keys from values.
31
32 When `comment_prefixes' is given, it will be used as the set of
Łukasz Langab25a7912010-12-17 01:32:29 +000033 substrings that prefix comments in empty lines. Comments can be
34 indented.
35
36 When `inline_comment_prefixes' is given, it will be used as the set of
37 substrings that prefix comments in non-empty lines.
Georg Brandl96a60ae2010-07-28 13:13:46 +000038
Fred Drakea4923622010-08-09 12:52:45 +000039 When `strict` is True, the parser won't allow for any section or option
40 duplicates while reading from a single source (file, string or
Łukasz Langab25a7912010-12-17 01:32:29 +000041 dictionary). Default is True.
Fred Drakea4923622010-08-09 12:52:45 +000042
Georg Brandl96a60ae2010-07-28 13:13:46 +000043 When `empty_lines_in_values' is False (default: True), each empty line
44 marks the end of an option. Otherwise, internal empty lines of
45 a multiline option are kept as part of the value.
46
47 When `allow_no_value' is True (default: False), options without
48 values are accepted; the value presented for these is None.
Guido van Rossum3d209861997-12-09 16:10:31 +000049
Barry Warsawf09f6a51999-01-26 22:01:37 +000050 sections()
Georg Brandl96a60ae2010-07-28 13:13:46 +000051 Return all the configuration section names, sans DEFAULT.
Guido van Rossum3d209861997-12-09 16:10:31 +000052
Guido van Rossuma5a24b71999-10-04 19:58:22 +000053 has_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000054 Return whether the given section exists.
Guido van Rossuma5a24b71999-10-04 19:58:22 +000055
Eric S. Raymond649685a2000-07-14 14:28:22 +000056 has_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +000057 Return whether the given option exists in the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +000058
Barry Warsawf09f6a51999-01-26 22:01:37 +000059 options(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000060 Return list of configuration options for the named section.
Guido van Rossum3d209861997-12-09 16:10:31 +000061
Georg Brandl8dcaa732010-07-29 12:17:40 +000062 read(filenames, encoding=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000063 Read and parse the list of named configuration files, given by
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000064 name. A single filename is also allowed. Non-existing files
Fred Drake82903142004-05-18 04:24:02 +000065 are ignored. Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000066
Fred Drakea4923622010-08-09 12:52:45 +000067 read_file(f, filename=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000068 Read and parse one configuration file, given as a file object.
Fred Drakea4923622010-08-09 12:52:45 +000069 The filename defaults to f.name; it is only used in error
70 messages (if f has no `name' attribute, the string `<???>' is used).
71
72 read_string(string)
73 Read configuration from a given string.
74
75 read_dict(dictionary)
76 Read configuration from a dictionary. Keys are section names,
77 values are dictionaries with keys and values that should be present
78 in the section. If the used dictionary type preserves order, sections
Fred Drakecc645b92010-09-04 04:35:34 +000079 and their keys will be added in order. Values are automatically
80 converted to strings.
Guido van Rossum3d209861997-12-09 16:10:31 +000081
Łukasz Langa26d513c2010-11-10 18:57:39 +000082 get(section, option, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000083 Return a string value for the named option. All % interpolations are
Barry Warsawf09f6a51999-01-26 22:01:37 +000084 expanded in the return values, based on the defaults passed into the
85 constructor and the DEFAULT section. Additional substitutions may be
86 provided using the `vars' argument, which must be a dictionary whose
Fred Drakecc645b92010-09-04 04:35:34 +000087 contents override any pre-existing defaults. If `option' is a key in
88 `vars', the value from `vars' is used.
Guido van Rossum3d209861997-12-09 16:10:31 +000089
Łukasz Langa26d513c2010-11-10 18:57:39 +000090 getint(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000091 Like get(), but convert value to an integer.
Guido van Rossum3d209861997-12-09 16:10:31 +000092
Łukasz Langa26d513c2010-11-10 18:57:39 +000093 getfloat(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000094 Like get(), but convert value to a float.
Guido van Rossum3d209861997-12-09 16:10:31 +000095
Łukasz Langa26d513c2010-11-10 18:57:39 +000096 getboolean(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000097 Like get(), but convert value to a boolean (currently case
Neal Norwitzf680cc42002-12-17 01:56:47 +000098 insensitively defined as 0, false, no, off for False, and 1, true,
99 yes, on for True). Returns False or True.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000100
Łukasz Langa71b37a52010-12-17 21:56:32 +0000101 items(section=_UNSET, raw=False, vars=None)
Łukasz Langa30574692012-12-31 02:18:20 +0100102 If section is given, return a list of tuples with (name, value) for
103 each option in the section. Otherwise, return a list of tuples with
104 (section_name, section_proxy) for each section, including DEFAULTSECT.
Fred Drake2ca041f2002-09-27 15:49:56 +0000105
Eric S. Raymond649685a2000-07-14 14:28:22 +0000106 remove_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000107 Remove the given file section and all its options.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000108
109 remove_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000110 Remove the given option from the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000111
112 set(section, option, value)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000113 Set the given option.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000114
Georg Brandl96a60ae2010-07-28 13:13:46 +0000115 write(fp, space_around_delimiters=True)
116 Write the configuration state in .ini format. If
117 `space_around_delimiters' is True (the default), delimiters
118 between keys and values are surrounded by spaces.
Guido van Rossum3d209861997-12-09 16:10:31 +0000119"""
120
Raymond Hettinger57d1a882011-02-23 00:46:28 +0000121from collections.abc import MutableMapping
Raymond Hettinger9fe1ccf2011-02-26 01:02:51 +0000122from collections import OrderedDict as _default_dict, ChainMap as _ChainMap
Łukasz Langa26d513c2010-11-10 18:57:39 +0000123import functools
Fred Drakea4923622010-08-09 12:52:45 +0000124import io
Łukasz Langa26d513c2010-11-10 18:57:39 +0000125import itertools
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000126import re
Georg Brandl96a60ae2010-07-28 13:13:46 +0000127import sys
Fred Drakea4923622010-08-09 12:52:45 +0000128import warnings
Guido van Rossum3d209861997-12-09 16:10:31 +0000129
Fred Drakea4923622010-08-09 12:52:45 +0000130__all__ = ["NoSectionError", "DuplicateOptionError", "DuplicateSectionError",
131 "NoOptionError", "InterpolationError", "InterpolationDepthError",
Fred Drake8d5dd982002-12-30 23:51:45 +0000132 "InterpolationSyntaxError", "ParsingError",
David Goodger1cbf2062004-10-03 15:55:09 +0000133 "MissingSectionHeaderError",
134 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +0000135 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000136
Guido van Rossum3d209861997-12-09 16:10:31 +0000137DEFAULTSECT = "DEFAULT"
138
Fred Drake2a37f9f2000-09-27 22:43:54 +0000139MAX_INTERPOLATION_DEPTH = 10
140
Guido van Rossum3d209861997-12-09 16:10:31 +0000141
Tim Peters88869f92001-01-14 23:36:06 +0000142
Guido van Rossum3d209861997-12-09 16:10:31 +0000143# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000144class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000145 """Base class for ConfigParser exceptions."""
146
Guido van Rossum3d209861997-12-09 16:10:31 +0000147 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000148 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000149 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000150
Guido van Rossum3d209861997-12-09 16:10:31 +0000151 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000152 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000153
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000154 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000155
Georg Brandl96a60ae2010-07-28 13:13:46 +0000156
Guido van Rossum3d209861997-12-09 16:10:31 +0000157class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000158 """Raised when no section matches a requested option."""
159
Guido van Rossum3d209861997-12-09 16:10:31 +0000160 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000161 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000162 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000163 self.args = (section, )
Guido van Rossum3d209861997-12-09 16:10:31 +0000164
Georg Brandl96a60ae2010-07-28 13:13:46 +0000165
Guido van Rossum3d209861997-12-09 16:10:31 +0000166class DuplicateSectionError(Error):
Fred Drakea4923622010-08-09 12:52:45 +0000167 """Raised when a section is repeated in an input source.
Fred Drake8d5dd982002-12-30 23:51:45 +0000168
Fred Drakea4923622010-08-09 12:52:45 +0000169 Possible repetitions that raise this exception are: multiple creation
170 using the API or in strict parsers when a section is found more than once
171 in a single input file, string or dictionary.
172 """
173
174 def __init__(self, section, source=None, lineno=None):
175 msg = [repr(section), " already exists"]
176 if source is not None:
Łukasz Langaf9b4eb42013-06-23 19:10:25 +0200177 message = ["While reading from ", repr(source)]
Fred Drakea4923622010-08-09 12:52:45 +0000178 if lineno is not None:
179 message.append(" [line {0:2d}]".format(lineno))
180 message.append(": section ")
181 message.extend(msg)
182 msg = message
183 else:
184 msg.insert(0, "Section ")
185 Error.__init__(self, "".join(msg))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000186 self.section = section
Fred Drakea4923622010-08-09 12:52:45 +0000187 self.source = source
188 self.lineno = lineno
189 self.args = (section, source, lineno)
190
191
192class DuplicateOptionError(Error):
193 """Raised by strict parsers when an option is repeated in an input source.
194
195 Current implementation raises this exception only when an option is found
196 more than once in a single file, string or dictionary.
197 """
198
199 def __init__(self, section, option, source=None, lineno=None):
200 msg = [repr(option), " in section ", repr(section),
201 " already exists"]
202 if source is not None:
Łukasz Langaf9b4eb42013-06-23 19:10:25 +0200203 message = ["While reading from ", repr(source)]
Fred Drakea4923622010-08-09 12:52:45 +0000204 if lineno is not None:
205 message.append(" [line {0:2d}]".format(lineno))
206 message.append(": option ")
207 message.extend(msg)
208 msg = message
209 else:
210 msg.insert(0, "Option ")
211 Error.__init__(self, "".join(msg))
212 self.section = section
213 self.option = option
214 self.source = source
215 self.lineno = lineno
216 self.args = (section, option, source, lineno)
Guido van Rossum3d209861997-12-09 16:10:31 +0000217
Georg Brandl96a60ae2010-07-28 13:13:46 +0000218
Guido van Rossum3d209861997-12-09 16:10:31 +0000219class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000220 """A requested option was not found."""
221
Guido van Rossum3d209861997-12-09 16:10:31 +0000222 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000223 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000224 (option, section))
225 self.option = option
226 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000227 self.args = (option, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000228
Georg Brandl96a60ae2010-07-28 13:13:46 +0000229
Guido van Rossum3d209861997-12-09 16:10:31 +0000230class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000231 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000232
Fred Drakee2c64912002-12-31 17:23:27 +0000233 def __init__(self, option, section, msg):
234 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000235 self.option = option
236 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000237 self.args = (option, section, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000238
Georg Brandl96a60ae2010-07-28 13:13:46 +0000239
Fred Drakee2c64912002-12-31 17:23:27 +0000240class InterpolationMissingOptionError(InterpolationError):
241 """A string substitution required a setting which was not available."""
242
243 def __init__(self, option, section, rawval, reference):
Robert Collinsac37ba02015-08-14 11:11:35 +1200244 msg = ("Bad value substitution: option {!r} in section {!r} contains "
245 "an interpolation key {!r} which is not a valid option name. "
246 "Raw value: {!r}".format(option, section, reference, rawval))
Fred Drakee2c64912002-12-31 17:23:27 +0000247 InterpolationError.__init__(self, option, section, msg)
248 self.reference = reference
Michael Foordbd6c0792010-07-25 23:09:25 +0000249 self.args = (option, section, rawval, reference)
Fred Drakee2c64912002-12-31 17:23:27 +0000250
Georg Brandl96a60ae2010-07-28 13:13:46 +0000251
Fred Drakee2c64912002-12-31 17:23:27 +0000252class InterpolationSyntaxError(InterpolationError):
Fred Drakea4923622010-08-09 12:52:45 +0000253 """Raised when the source text contains invalid syntax.
254
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000255 Current implementation raises this exception when the source text into
256 which substitutions are made does not conform to the required syntax.
Fred Drakea4923622010-08-09 12:52:45 +0000257 """
Neal Norwitzce1d9442002-12-30 23:38:47 +0000258
Georg Brandl96a60ae2010-07-28 13:13:46 +0000259
Fred Drakee2c64912002-12-31 17:23:27 +0000260class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000261 """Raised when substitutions are nested too deeply."""
262
Fred Drake2a37f9f2000-09-27 22:43:54 +0000263 def __init__(self, option, section, rawval):
Robert Collinsac37ba02015-08-14 11:11:35 +1200264 msg = ("Recursion limit exceeded in value substitution: option {!r} "
265 "in section {!r} contains an interpolation key which "
266 "cannot be substituted in {} steps. Raw value: {!r}"
267 "".format(option, section, MAX_INTERPOLATION_DEPTH,
268 rawval))
Fred Drakee2c64912002-12-31 17:23:27 +0000269 InterpolationError.__init__(self, option, section, msg)
Michael Foordbd6c0792010-07-25 23:09:25 +0000270 self.args = (option, section, rawval)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000271
Georg Brandl96a60ae2010-07-28 13:13:46 +0000272
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000273class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000274 """Raised when a configuration file does not follow legal syntax."""
275
Fred Drakea4923622010-08-09 12:52:45 +0000276 def __init__(self, source=None, filename=None):
277 # Exactly one of `source'/`filename' arguments has to be given.
278 # `filename' kept for compatibility.
279 if filename and source:
280 raise ValueError("Cannot specify both `filename' and `source'. "
281 "Use `source'.")
282 elif not filename and not source:
283 raise ValueError("Required argument `source' not given.")
284 elif filename:
285 source = filename
Serhiy Storchakabc27a052014-02-06 22:49:45 +0200286 Error.__init__(self, 'Source contains parsing errors: %r' % source)
Fred Drakea4923622010-08-09 12:52:45 +0000287 self.source = source
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000288 self.errors = []
Fred Drakea4923622010-08-09 12:52:45 +0000289 self.args = (source, )
290
291 @property
292 def filename(self):
293 """Deprecated, use `source'."""
294 warnings.warn(
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000295 "The 'filename' attribute will be removed in future versions. "
Fred Drakea4923622010-08-09 12:52:45 +0000296 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000297 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000298 )
299 return self.source
300
301 @filename.setter
302 def filename(self, value):
303 """Deprecated, user `source'."""
304 warnings.warn(
305 "The 'filename' attribute will be removed in future versions. "
306 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000307 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000308 )
309 self.source = value
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000310
311 def append(self, lineno, line):
312 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000313 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000314
Georg Brandl96a60ae2010-07-28 13:13:46 +0000315
Fred Drake2a37f9f2000-09-27 22:43:54 +0000316class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000317 """Raised when a key-value pair is found before any section header."""
318
Fred Drake2a37f9f2000-09-27 22:43:54 +0000319 def __init__(self, filename, lineno, line):
320 Error.__init__(
321 self,
Serhiy Storchakabc27a052014-02-06 22:49:45 +0200322 'File contains no section headers.\nfile: %r, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000323 (filename, lineno, line))
Fred Drakea4923622010-08-09 12:52:45 +0000324 self.source = filename
Fred Drake2a37f9f2000-09-27 22:43:54 +0000325 self.lineno = lineno
326 self.line = line
Michael Foordbd6c0792010-07-25 23:09:25 +0000327 self.args = (filename, lineno, line)
Guido van Rossum3d209861997-12-09 16:10:31 +0000328
Georg Brandl96a60ae2010-07-28 13:13:46 +0000329
Fred Drakecc645b92010-09-04 04:35:34 +0000330# Used in parser getters to indicate the default behaviour when a specific
331# option is not found it to raise an exception. Created to enable `None' as
332# a valid fallback value.
333_UNSET = object()
334
335
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000336class Interpolation:
337 """Dummy interpolation that passes the value through with no changes."""
338
339 def before_get(self, parser, section, option, value, defaults):
340 return value
341
342 def before_set(self, parser, section, option, value):
343 return value
344
345 def before_read(self, parser, section, option, value):
346 return value
347
348 def before_write(self, parser, section, option, value):
349 return value
350
351
352class BasicInterpolation(Interpolation):
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000353 """Interpolation as implemented in the classic ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000354
355 The option values can contain format strings which refer to other values in
356 the same section, or values in the special default section.
357
358 For example:
359
360 something: %(dir)s/whatever
361
362 would resolve the "%(dir)s" to the value of dir. All reference
363 expansions are done late, on demand. If a user needs to use a bare % in
Ezio Melottie130a522011-10-19 10:58:56 +0300364 a configuration file, she can escape it by writing %%. Other % usage
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000365 is considered a user error and raises `InterpolationSyntaxError'."""
366
367 _KEYCRE = re.compile(r"%\(([^)]+)\)s")
368
369 def before_get(self, parser, section, option, value, defaults):
370 L = []
371 self._interpolate_some(parser, option, L, value, section, defaults, 1)
372 return ''.join(L)
373
374 def before_set(self, parser, section, option, value):
375 tmp_value = value.replace('%%', '') # escaped percent signs
376 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
377 if '%' in tmp_value:
378 raise ValueError("invalid interpolation syntax in %r at "
379 "position %d" % (value, tmp_value.find('%')))
380 return value
381
382 def _interpolate_some(self, parser, option, accum, rest, section, map,
383 depth):
Robert Collinsac37ba02015-08-14 11:11:35 +1200384 rawval = parser.get(section, option, raw=True, fallback=rest)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000385 if depth > MAX_INTERPOLATION_DEPTH:
Robert Collinsac37ba02015-08-14 11:11:35 +1200386 raise InterpolationDepthError(option, section, rawval)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000387 while rest:
388 p = rest.find("%")
389 if p < 0:
390 accum.append(rest)
391 return
392 if p > 0:
393 accum.append(rest[:p])
394 rest = rest[p:]
395 # p is no longer used
396 c = rest[1:2]
397 if c == "%":
398 accum.append("%")
399 rest = rest[2:]
400 elif c == "(":
401 m = self._KEYCRE.match(rest)
402 if m is None:
403 raise InterpolationSyntaxError(option, section,
404 "bad interpolation variable reference %r" % rest)
405 var = parser.optionxform(m.group(1))
406 rest = rest[m.end():]
407 try:
408 v = map[var]
409 except KeyError:
410 raise InterpolationMissingOptionError(
Robert Collinsac37ba02015-08-14 11:11:35 +1200411 option, section, rawval, var)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000412 if "%" in v:
413 self._interpolate_some(parser, option, accum, v,
414 section, map, depth + 1)
415 else:
416 accum.append(v)
417 else:
418 raise InterpolationSyntaxError(
419 option, section,
420 "'%%' must be followed by '%%' or '(', "
421 "found: %r" % (rest,))
422
423
424class ExtendedInterpolation(Interpolation):
425 """Advanced variant of interpolation, supports the syntax used by
426 `zc.buildout'. Enables interpolation between sections."""
427
428 _KEYCRE = re.compile(r"\$\{([^}]+)\}")
429
430 def before_get(self, parser, section, option, value, defaults):
431 L = []
432 self._interpolate_some(parser, option, L, value, section, defaults, 1)
433 return ''.join(L)
434
435 def before_set(self, parser, section, option, value):
436 tmp_value = value.replace('$$', '') # escaped dollar signs
437 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
438 if '$' in tmp_value:
439 raise ValueError("invalid interpolation syntax in %r at "
Łukasz Langafa608182013-04-24 01:25:18 +0200440 "position %d" % (value, tmp_value.find('$')))
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000441 return value
442
443 def _interpolate_some(self, parser, option, accum, rest, section, map,
444 depth):
Robert Collinsac37ba02015-08-14 11:11:35 +1200445 rawval = parser.get(section, option, raw=True, fallback=rest)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000446 if depth > MAX_INTERPOLATION_DEPTH:
Robert Collinsac37ba02015-08-14 11:11:35 +1200447 raise InterpolationDepthError(option, section, rawval)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000448 while rest:
449 p = rest.find("$")
450 if p < 0:
451 accum.append(rest)
452 return
453 if p > 0:
454 accum.append(rest[:p])
455 rest = rest[p:]
456 # p is no longer used
457 c = rest[1:2]
458 if c == "$":
459 accum.append("$")
460 rest = rest[2:]
461 elif c == "{":
462 m = self._KEYCRE.match(rest)
463 if m is None:
464 raise InterpolationSyntaxError(option, section,
465 "bad interpolation variable reference %r" % rest)
Łukasz Langae698cd52011-04-28 10:58:57 +0200466 path = m.group(1).split(':')
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000467 rest = rest[m.end():]
468 sect = section
469 opt = option
470 try:
471 if len(path) == 1:
Łukasz Langae698cd52011-04-28 10:58:57 +0200472 opt = parser.optionxform(path[0])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000473 v = map[opt]
474 elif len(path) == 2:
475 sect = path[0]
Łukasz Langae698cd52011-04-28 10:58:57 +0200476 opt = parser.optionxform(path[1])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000477 v = parser.get(sect, opt, raw=True)
478 else:
479 raise InterpolationSyntaxError(
480 option, section,
481 "More than one ':' found: %r" % (rest,))
Łukasz Langa71b37a52010-12-17 21:56:32 +0000482 except (KeyError, NoSectionError, NoOptionError):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000483 raise InterpolationMissingOptionError(
Robert Collinsac37ba02015-08-14 11:11:35 +1200484 option, section, rawval, ":".join(path))
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000485 if "$" in v:
486 self._interpolate_some(parser, opt, accum, v, sect,
487 dict(parser.items(sect, raw=True)),
488 depth + 1)
489 else:
490 accum.append(v)
491 else:
492 raise InterpolationSyntaxError(
493 option, section,
494 "'$' must be followed by '$' or '{', "
495 "found: %r" % (rest,))
496
497
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000498class LegacyInterpolation(Interpolation):
499 """Deprecated interpolation used in old versions of ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000500 Use BasicInterpolation or ExtendedInterpolation instead."""
501
502 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
503
504 def before_get(self, parser, section, option, value, vars):
505 rawval = value
506 depth = MAX_INTERPOLATION_DEPTH
507 while depth: # Loop through this until it's done
508 depth -= 1
509 if value and "%(" in value:
510 replace = functools.partial(self._interpolation_replace,
511 parser=parser)
512 value = self._KEYCRE.sub(replace, value)
513 try:
514 value = value % vars
515 except KeyError as e:
516 raise InterpolationMissingOptionError(
517 option, section, rawval, e.args[0])
518 else:
519 break
520 if value and "%(" in value:
521 raise InterpolationDepthError(option, section, rawval)
522 return value
523
524 def before_set(self, parser, section, option, value):
525 return value
526
527 @staticmethod
528 def _interpolation_replace(match, parser):
529 s = match.group(1)
530 if s is None:
531 return match.group()
532 else:
533 return "%%(%s)s" % parser.optionxform(s)
534
535
Łukasz Langa26d513c2010-11-10 18:57:39 +0000536class RawConfigParser(MutableMapping):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000537 """ConfigParser that does not do interpolation."""
538
539 # Regular expressions for parsing section headers and options
540 _SECT_TMPL = r"""
541 \[ # [
542 (?P<header>[^]]+) # very permissive!
543 \] # ]
544 """
545 _OPT_TMPL = r"""
546 (?P<option>.*?) # very permissive!
547 \s*(?P<vi>{delim})\s* # any number of space/tab,
548 # followed by any of the
549 # allowed delimiters,
550 # followed by any space/tab
551 (?P<value>.*)$ # everything up to eol
552 """
553 _OPT_NV_TMPL = r"""
554 (?P<option>.*?) # very permissive!
555 \s*(?: # any number of space/tab,
556 (?P<vi>{delim})\s* # optionally followed by
557 # any of the allowed
558 # delimiters, followed by any
559 # space/tab
560 (?P<value>.*))?$ # everything up to eol
561 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000562 # Interpolation algorithm to be used if the user does not specify another
563 _DEFAULT_INTERPOLATION = Interpolation()
Georg Brandl96a60ae2010-07-28 13:13:46 +0000564 # Compiled regular expression for matching sections
565 SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
566 # Compiled regular expression for matching options with typical separators
567 OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
568 # Compiled regular expression for matching options with optional values
569 # delimited using typical separators
570 OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
571 # Compiled regular expression for matching leading whitespace in a line
572 NONSPACECRE = re.compile(r"\S")
Fred Drakecc645b92010-09-04 04:35:34 +0000573 # Possible boolean values in the configuration.
574 BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
575 '0': False, 'no': False, 'false': False, 'off': False}
Georg Brandl96a60ae2010-07-28 13:13:46 +0000576
Fred Drake03c44a32010-02-19 06:08:41 +0000577 def __init__(self, defaults=None, dict_type=_default_dict,
Fred Drakea4923622010-08-09 12:52:45 +0000578 allow_no_value=False, *, delimiters=('=', ':'),
Łukasz Langab25a7912010-12-17 01:32:29 +0000579 comment_prefixes=('#', ';'), inline_comment_prefixes=None,
580 strict=True, empty_lines_in_values=True,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000581 default_section=DEFAULTSECT,
582 interpolation=_UNSET):
583
Thomas Wouters89f507f2006-12-13 04:49:30 +0000584 self._dict = dict_type
585 self._sections = self._dict()
586 self._defaults = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000587 self._proxies = self._dict()
Łukasz Langac264c092010-11-20 16:15:37 +0000588 self._proxies[default_section] = SectionProxy(self, default_section)
David Goodger68a1abd2004-10-03 15:40:25 +0000589 if defaults:
590 for key, value in defaults.items():
591 self._defaults[self.optionxform(key)] = value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000592 self._delimiters = tuple(delimiters)
593 if delimiters == ('=', ':'):
594 self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
595 else:
Fred Drakea4923622010-08-09 12:52:45 +0000596 d = "|".join(re.escape(d) for d in delimiters)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000597 if allow_no_value:
Fred Drakea4923622010-08-09 12:52:45 +0000598 self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000599 re.VERBOSE)
600 else:
Fred Drakea4923622010-08-09 12:52:45 +0000601 self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000602 re.VERBOSE)
Łukasz Langab25a7912010-12-17 01:32:29 +0000603 self._comment_prefixes = tuple(comment_prefixes or ())
604 self._inline_comment_prefixes = tuple(inline_comment_prefixes or ())
Fred Drakea4923622010-08-09 12:52:45 +0000605 self._strict = strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000606 self._allow_no_value = allow_no_value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000607 self._empty_lines_in_values = empty_lines_in_values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000608 self.default_section=default_section
Łukasz Langa1aa422f2011-04-28 17:03:45 +0200609 self._interpolation = interpolation
610 if self._interpolation is _UNSET:
611 self._interpolation = self._DEFAULT_INTERPOLATION
612 if self._interpolation is None:
613 self._interpolation = Interpolation()
Guido van Rossum3d209861997-12-09 16:10:31 +0000614
615 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000616 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000617
618 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000619 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000620 # self._sections will never have [DEFAULT] in it
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000621 return list(self._sections.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000622
623 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000624 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000625
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000626 Raise DuplicateSectionError if a section by the specified name
Łukasz Langac264c092010-11-20 16:15:37 +0000627 already exists. Raise ValueError if name is DEFAULT.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000628 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000629 if section == self.default_section:
Łukasz Langa3a11e712010-12-03 22:15:19 +0000630 raise ValueError('Invalid section name: %r' % section)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000631
Fred Drakefce65572002-10-25 18:08:18 +0000632 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000633 raise DuplicateSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000634 self._sections[section] = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000635 self._proxies[section] = SectionProxy(self, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000636
637 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000638 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000639
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000640 The DEFAULT section is not acknowledged.
641 """
Fred Drakefce65572002-10-25 18:08:18 +0000642 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000643
644 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000645 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000646 try:
Fred Drakefce65572002-10-25 18:08:18 +0000647 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000648 except KeyError:
649 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000650 opts.update(self._defaults)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000651 return list(opts.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000652
Georg Brandl8dcaa732010-07-29 12:17:40 +0000653 def read(self, filenames, encoding=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000654 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000655
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000656 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000657 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000658 configuration file locations (e.g. current directory, user's
659 home directory, systemwide directory), and all existing
660 configuration files in the list will be read. A single
661 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000662
663 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000664 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000665 if isinstance(filenames, str):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000666 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000667 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000668 for filename in filenames:
669 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000670 with open(filename, encoding=encoding) as fp:
671 self._read(fp, filename)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200672 except OSError:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000673 continue
Fred Drake82903142004-05-18 04:24:02 +0000674 read_ok.append(filename)
675 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000676
Fred Drakea4923622010-08-09 12:52:45 +0000677 def read_file(self, f, source=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000678 """Like read() but the argument must be a file-like object.
679
Łukasz Langadaab1c82011-04-27 18:10:05 +0200680 The `f' argument must be iterable, returning one line at a time.
681 Optional second argument is the `source' specifying the name of the
682 file being read. If not given, it is taken from f.name. If `f' has no
683 `name' attribute, `<???>' is used.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000684 """
Fred Drakea4923622010-08-09 12:52:45 +0000685 if source is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000686 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000687 source = f.name
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000688 except AttributeError:
Fred Drakea4923622010-08-09 12:52:45 +0000689 source = '<???>'
690 self._read(f, source)
691
692 def read_string(self, string, source='<string>'):
693 """Read configuration from a given string."""
694 sfile = io.StringIO(string)
695 self.read_file(sfile, source)
696
697 def read_dict(self, dictionary, source='<dict>'):
698 """Read configuration from a dictionary.
699
700 Keys are section names, values are dictionaries with keys and values
701 that should be present in the section. If the used dictionary type
702 preserves order, sections and their keys will be added in order.
703
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000704 All types held in the dictionary are converted to strings during
705 reading, including section names, option names and keys.
706
Fred Drakea4923622010-08-09 12:52:45 +0000707 Optional second argument is the `source' specifying the name of the
708 dictionary being read.
709 """
710 elements_added = set()
711 for section, keys in dictionary.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000712 section = str(section)
Fred Drakea4923622010-08-09 12:52:45 +0000713 try:
714 self.add_section(section)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000715 except (DuplicateSectionError, ValueError):
Fred Drakea4923622010-08-09 12:52:45 +0000716 if self._strict and section in elements_added:
717 raise
Łukasz Langa71b37a52010-12-17 21:56:32 +0000718 elements_added.add(section)
Fred Drakea4923622010-08-09 12:52:45 +0000719 for key, value in keys.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000720 key = self.optionxform(str(key))
Fred Drakecc645b92010-09-04 04:35:34 +0000721 if value is not None:
722 value = str(value)
Fred Drakea4923622010-08-09 12:52:45 +0000723 if self._strict and (section, key) in elements_added:
724 raise DuplicateOptionError(section, key, source)
725 elements_added.add((section, key))
726 self.set(section, key, value)
727
728 def readfp(self, fp, filename=None):
729 """Deprecated, use read_file instead."""
730 warnings.warn(
731 "This method will be removed in future versions. "
732 "Use 'parser.read_file()' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000733 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000734 )
735 self.read_file(fp, source=filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000736
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000737 def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000738 """Get an option value for a given section.
739
740 If `vars' is provided, it must be a dictionary. The option is looked up
741 in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000742 If the key is not found and `fallback' is provided, it is used as
743 a fallback value. `None' can be provided as a `fallback' value.
744
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000745 If interpolation is enabled and the optional argument `raw' is False,
746 all interpolations are expanded in the return values.
747
748 Arguments `raw', `vars', and `fallback' are keyword only.
749
750 The section DEFAULT is special.
Fred Drakecc645b92010-09-04 04:35:34 +0000751 """
752 try:
753 d = self._unify_values(section, vars)
754 except NoSectionError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000755 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000756 raise
Fred Drakefce65572002-10-25 18:08:18 +0000757 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000758 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000759 option = self.optionxform(option)
760 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000761 value = d[option]
Fred Drakecc645b92010-09-04 04:35:34 +0000762 except KeyError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000763 if fallback is _UNSET:
Fred Drakefce65572002-10-25 18:08:18 +0000764 raise NoOptionError(option, section)
Fred Drakecc645b92010-09-04 04:35:34 +0000765 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000766 return fallback
Fred Drake2a37f9f2000-09-27 22:43:54 +0000767
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000768 if raw or value is None:
769 return value
770 else:
771 return self._interpolation.before_get(self, section, option, value,
772 d)
Fred Drake2ca041f2002-09-27 15:49:56 +0000773
Łukasz Langa26d513c2010-11-10 18:57:39 +0000774 def _get(self, section, conv, option, **kwargs):
775 return conv(self.get(section, option, **kwargs))
Guido van Rossum3d209861997-12-09 16:10:31 +0000776
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000777 def getint(self, section, option, *, raw=False, vars=None,
778 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000779 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000780 return self._get(section, int, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000781 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000782 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000783 raise
784 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000785 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000786
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000787 def getfloat(self, section, option, *, raw=False, vars=None,
788 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000789 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000790 return self._get(section, float, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000791 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000792 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000793 raise
794 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000795 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000796
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000797 def getboolean(self, section, option, *, raw=False, vars=None,
798 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000799 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000800 return self._get(section, self._convert_to_boolean, option,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000801 raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000802 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000803 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000804 raise
805 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000806 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000807
Łukasz Langa71b37a52010-12-17 21:56:32 +0000808 def items(self, section=_UNSET, raw=False, vars=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000809 """Return a list of (name, value) tuples for each option in a section.
810
811 All % interpolations are expanded in the return values, based on the
812 defaults passed into the constructor, unless the optional argument
813 `raw' is true. Additional substitutions may be provided using the
814 `vars' argument, which must be a dictionary whose contents overrides
815 any pre-existing defaults.
816
817 The section DEFAULT is special.
818 """
Łukasz Langa71b37a52010-12-17 21:56:32 +0000819 if section is _UNSET:
820 return super().items()
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000821 d = self._defaults.copy()
822 try:
823 d.update(self._sections[section])
824 except KeyError:
825 if section != self.default_section:
826 raise NoSectionError(section)
827 # Update with the entry specific variables
828 if vars:
829 for key, value in vars.items():
830 d[self.optionxform(key)] = value
Łukasz Langa24bcc612010-12-04 11:48:11 +0000831 value_getter = lambda option: self._interpolation.before_get(self,
832 section, option, d[option], d)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000833 if raw:
Łukasz Langa24bcc612010-12-04 11:48:11 +0000834 value_getter = lambda option: d[option]
835 return [(option, value_getter(option)) for option in d.keys()]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000836
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100837 def popitem(self):
838 """Remove a section from the parser and return it as
839 a (section_name, section_proxy) tuple. If no section is present, raise
840 KeyError.
841
842 The section DEFAULT is never returned because it cannot be removed.
843 """
844 for key in self.sections():
845 value = self[key]
846 del self[key]
847 return key, value
848 raise KeyError
849
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000850 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000851 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000852
Eric S. Raymond417c4892000-07-10 18:11:00 +0000853 def has_option(self, section, option):
Łukasz Langa71b37a52010-12-17 21:56:32 +0000854 """Check for the existence of a given option in a given section.
855 If the specified `section' is None or an empty string, DEFAULT is
856 assumed. If the specified `section' does not exist, returns False."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000857 if not section or section == self.default_section:
Fred Drakec2ff9052002-09-27 15:33:11 +0000858 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000859 return option in self._defaults
860 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000861 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000862 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000863 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000864 return (option in self._sections[section]
865 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000866
Fred Drake03c44a32010-02-19 06:08:41 +0000867 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000868 """Set an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000869 if value:
870 value = self._interpolation.before_set(self, section, option,
871 value)
872 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000873 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000874 else:
875 try:
Fred Drakefce65572002-10-25 18:08:18 +0000876 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000877 except KeyError:
878 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000879 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000880
Georg Brandl96a60ae2010-07-28 13:13:46 +0000881 def write(self, fp, space_around_delimiters=True):
882 """Write an .ini-format representation of the configuration state.
883
884 If `space_around_delimiters' is True (the default), delimiters
885 between keys and values are surrounded by spaces.
886 """
887 if space_around_delimiters:
888 d = " {} ".format(self._delimiters[0])
889 else:
890 d = self._delimiters[0]
Fred Drakefce65572002-10-25 18:08:18 +0000891 if self._defaults:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000892 self._write_section(fp, self.default_section,
Łukasz Langac264c092010-11-20 16:15:37 +0000893 self._defaults.items(), d)
Fred Drakefce65572002-10-25 18:08:18 +0000894 for section in self._sections:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000895 self._write_section(fp, section,
896 self._sections[section].items(), d)
897
898 def _write_section(self, fp, section_name, section_items, delimiter):
899 """Write a single section to the specified `fp'."""
900 fp.write("[{}]\n".format(section_name))
901 for key, value in section_items:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000902 value = self._interpolation.before_write(self, section_name, key,
903 value)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000904 if value is not None or not self._allow_no_value:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000905 value = delimiter + str(value).replace('\n', '\n\t')
906 else:
907 value = ""
908 fp.write("{}{}\n".format(key, value))
909 fp.write("\n")
Eric S. Raymond417c4892000-07-10 18:11:00 +0000910
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000911 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000912 """Remove an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000913 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000914 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000915 else:
916 try:
Fred Drakefce65572002-10-25 18:08:18 +0000917 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000918 except KeyError:
919 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000920 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000921 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000922 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000923 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000924 return existed
925
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000926 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000927 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000928 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000929 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000930 del self._sections[section]
Łukasz Langa49afa382010-11-11 19:53:23 +0000931 del self._proxies[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000932 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000933
Łukasz Langa26d513c2010-11-10 18:57:39 +0000934 def __getitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000935 if key != self.default_section and not self.has_section(key):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000936 raise KeyError(key)
Łukasz Langa49afa382010-11-11 19:53:23 +0000937 return self._proxies[key]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000938
939 def __setitem__(self, key, value):
940 # To conform with the mapping protocol, overwrites existing values in
941 # the section.
942
943 # XXX this is not atomic if read_dict fails at any point. Then again,
944 # no update method in configparser is atomic in this implementation.
Łukasz Langa02101942012-12-31 13:55:11 +0100945 if key == self.default_section:
946 self._defaults.clear()
Łukasz Langaa821f822013-01-01 22:33:19 +0100947 elif key in self._sections:
948 self._sections[key].clear()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000949 self.read_dict({key: value})
950
951 def __delitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000952 if key == self.default_section:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000953 raise ValueError("Cannot remove the default section.")
954 if not self.has_section(key):
955 raise KeyError(key)
956 self.remove_section(key)
957
958 def __contains__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000959 return key == self.default_section or self.has_section(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000960
961 def __len__(self):
962 return len(self._sections) + 1 # the default section
963
964 def __iter__(self):
965 # XXX does it break when underlying container state changed?
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000966 return itertools.chain((self.default_section,), self._sections.keys())
Łukasz Langa26d513c2010-11-10 18:57:39 +0000967
Fred Drakefce65572002-10-25 18:08:18 +0000968 def _read(self, fp, fpname):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000969 """Parse a sectioned configuration file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000970
Fred Drakea4923622010-08-09 12:52:45 +0000971 Each section in a configuration file contains a header, indicated by
972 a name in square brackets (`[]'), plus key/value options, indicated by
Georg Brandl96a60ae2010-07-28 13:13:46 +0000973 `name' and `value' delimited with a specific substring (`=' or `:' by
974 default).
975
Fred Drakea4923622010-08-09 12:52:45 +0000976 Values can span multiple lines, as long as they are indented deeper
977 than the first line of the value. Depending on the parser's mode, blank
978 lines may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000979
980 Configuration files may include comments, prefixed by specific
Fred Drakea4923622010-08-09 12:52:45 +0000981 characters (`#' and `;' by default). Comments may appear on their own
982 in an otherwise empty line or may be entered in lines holding values or
Georg Brandl96a60ae2010-07-28 13:13:46 +0000983 section names.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000984 """
Fred Drakea4923622010-08-09 12:52:45 +0000985 elements_added = set()
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000986 cursect = None # None, or a dictionary
Fred Drakea4923622010-08-09 12:52:45 +0000987 sectname = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000988 optname = None
989 lineno = 0
Georg Brandl96a60ae2010-07-28 13:13:46 +0000990 indent_level = 0
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000991 e = None # None, or an exception
Georg Brandl96a60ae2010-07-28 13:13:46 +0000992 for lineno, line in enumerate(fp, start=1):
Łukasz Langacba24322012-07-07 18:54:08 +0200993 comment_start = sys.maxsize
Georg Brandl96a60ae2010-07-28 13:13:46 +0000994 # strip inline comments
Łukasz Langacba24322012-07-07 18:54:08 +0200995 inline_prefixes = {p: -1 for p in self._inline_comment_prefixes}
996 while comment_start == sys.maxsize and inline_prefixes:
997 next_prefixes = {}
998 for prefix, index in inline_prefixes.items():
999 index = line.find(prefix, index+1)
1000 if index == -1:
1001 continue
1002 next_prefixes[prefix] = index
1003 if index == 0 or (index > 0 and line[index-1].isspace()):
1004 comment_start = min(comment_start, index)
1005 inline_prefixes = next_prefixes
Łukasz Langab25a7912010-12-17 01:32:29 +00001006 # strip full line comments
1007 for prefix in self._comment_prefixes:
1008 if line.strip().startswith(prefix):
1009 comment_start = 0
1010 break
Łukasz Langacba24322012-07-07 18:54:08 +02001011 if comment_start == sys.maxsize:
1012 comment_start = None
Georg Brandl96a60ae2010-07-28 13:13:46 +00001013 value = line[:comment_start].strip()
1014 if not value:
Georg Brandlf206d0e2010-07-29 11:56:20 +00001015 if self._empty_lines_in_values:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001016 # add empty line to the value, but only if there was no
1017 # comment on the line
Georg Brandlf206d0e2010-07-29 11:56:20 +00001018 if (comment_start is None and
1019 cursect is not None and
1020 optname and
1021 cursect[optname] is not None):
1022 cursect[optname].append('') # newlines added at join
Georg Brandl96a60ae2010-07-28 13:13:46 +00001023 else:
1024 # empty line marks end of value
1025 indent_level = sys.maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001026 continue
1027 # continuation line?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001028 first_nonspace = self.NONSPACECRE.search(line)
1029 cur_indent_level = first_nonspace.start() if first_nonspace else 0
1030 if (cursect is not None and optname and
1031 cur_indent_level > indent_level):
1032 cursect[optname].append(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001033 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001034 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001035 indent_level = cur_indent_level
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001036 # is it a section header?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001037 mo = self.SECTCRE.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001038 if mo:
1039 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +00001040 if sectname in self._sections:
Fred Drakea4923622010-08-09 12:52:45 +00001041 if self._strict and sectname in elements_added:
1042 raise DuplicateSectionError(sectname, fpname,
1043 lineno)
Fred Drakefce65572002-10-25 18:08:18 +00001044 cursect = self._sections[sectname]
Fred Drakea4923622010-08-09 12:52:45 +00001045 elements_added.add(sectname)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001046 elif sectname == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001047 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001048 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001049 cursect = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +00001050 self._sections[sectname] = cursect
Łukasz Langa49afa382010-11-11 19:53:23 +00001051 self._proxies[sectname] = SectionProxy(self, sectname)
Fred Drakea4923622010-08-09 12:52:45 +00001052 elements_added.add(sectname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001053 # So sections can't start with a continuation line
1054 optname = None
1055 # no section header in the file?
1056 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001057 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001058 # an option line?
1059 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001060 mo = self._optcre.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001061 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +00001062 optname, vi, optval = mo.group('option', 'vi', 'value')
Georg Brandl96a60ae2010-07-28 13:13:46 +00001063 if not optname:
1064 e = self._handle_error(e, fpname, lineno, line)
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001065 optname = self.optionxform(optname.rstrip())
Fred Drakea4923622010-08-09 12:52:45 +00001066 if (self._strict and
1067 (sectname, optname) in elements_added):
1068 raise DuplicateOptionError(sectname, optname,
1069 fpname, lineno)
1070 elements_added.add((sectname, optname))
Fred Drake03c44a32010-02-19 06:08:41 +00001071 # This check is fine because the OPTCRE cannot
1072 # match if it would set optval to None
1073 if optval is not None:
Fred Drake03c44a32010-02-19 06:08:41 +00001074 optval = optval.strip()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001075 cursect[optname] = [optval]
1076 else:
1077 # valueless option handling
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001078 cursect[optname] = None
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001079 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001080 # a non-fatal parsing error occurred. set up the
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001081 # exception but keep going. the exception will be
1082 # raised at the end of the file and will contain a
1083 # list of all bogus lines
Georg Brandl96a60ae2010-07-28 13:13:46 +00001084 e = self._handle_error(e, fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001085 # if any parsing errors occurred, raise an exception
1086 if e:
1087 raise e
Georg Brandl96a60ae2010-07-28 13:13:46 +00001088 self._join_multiline_values()
Fred Drakefce65572002-10-25 18:08:18 +00001089
Georg Brandl96a60ae2010-07-28 13:13:46 +00001090 def _join_multiline_values(self):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001091 defaults = self.default_section, self._defaults
1092 all_sections = itertools.chain((defaults,),
1093 self._sections.items())
1094 for section, options in all_sections:
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001095 for name, val in options.items():
1096 if isinstance(val, list):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001097 val = '\n'.join(val).rstrip()
1098 options[name] = self._interpolation.before_read(self,
1099 section,
1100 name, val)
Fred Drakefce65572002-10-25 18:08:18 +00001101
Georg Brandl96a60ae2010-07-28 13:13:46 +00001102 def _handle_error(self, exc, fpname, lineno, line):
1103 if not exc:
1104 exc = ParsingError(fpname)
1105 exc.append(lineno, repr(line))
1106 return exc
1107
Fred Drakecc645b92010-09-04 04:35:34 +00001108 def _unify_values(self, section, vars):
Raymond Hettingerddb52402011-02-21 19:42:11 +00001109 """Create a sequence of lookups with 'vars' taking priority over
1110 the 'section' which takes priority over the DEFAULTSECT.
1111
Fred Drakefce65572002-10-25 18:08:18 +00001112 """
Raymond Hettingerddb52402011-02-21 19:42:11 +00001113 sectiondict = {}
Fred Drakefce65572002-10-25 18:08:18 +00001114 try:
Raymond Hettingerddb52402011-02-21 19:42:11 +00001115 sectiondict = self._sections[section]
Fred Drakefce65572002-10-25 18:08:18 +00001116 except KeyError:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001117 if section != self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001118 raise NoSectionError(section)
1119 # Update with the entry specific variables
Raymond Hettingerddb52402011-02-21 19:42:11 +00001120 vardict = {}
David Goodger68a1abd2004-10-03 15:40:25 +00001121 if vars:
1122 for key, value in vars.items():
Fred Drakecc645b92010-09-04 04:35:34 +00001123 if value is not None:
1124 value = str(value)
Raymond Hettingerddb52402011-02-21 19:42:11 +00001125 vardict[self.optionxform(key)] = value
1126 return _ChainMap(vardict, sectiondict, self._defaults)
Fred Drakecc645b92010-09-04 04:35:34 +00001127
1128 def _convert_to_boolean(self, value):
1129 """Return a boolean value translating from other types if necessary.
1130 """
1131 if value.lower() not in self.BOOLEAN_STATES:
1132 raise ValueError('Not a boolean: %s' % value)
1133 return self.BOOLEAN_STATES[value.lower()]
1134
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001135 def _validate_value_types(self, *, section="", option="", value=""):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001136 """Raises a TypeError for non-string values.
1137
1138 The only legal non-string value if we allow valueless
1139 options is None, so we need to check if the value is a
1140 string if:
1141 - we do not allow valueless options, or
1142 - we allow valueless options but the value is not None
1143
1144 For compatibility reasons this method is not used in classic set()
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001145 for RawConfigParsers. It is invoked in every case for mapping protocol
1146 access and in ConfigParser.set().
Łukasz Langa26d513c2010-11-10 18:57:39 +00001147 """
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001148 if not isinstance(section, str):
1149 raise TypeError("section names must be strings")
1150 if not isinstance(option, str):
1151 raise TypeError("option keys must be strings")
Łukasz Langa26d513c2010-11-10 18:57:39 +00001152 if not self._allow_no_value or value:
1153 if not isinstance(value, str):
1154 raise TypeError("option values must be strings")
1155
1156
Fred Drakecc645b92010-09-04 04:35:34 +00001157class ConfigParser(RawConfigParser):
1158 """ConfigParser implementing interpolation."""
1159
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001160 _DEFAULT_INTERPOLATION = BasicInterpolation()
David Goodger1cbf2062004-10-03 15:55:09 +00001161
Fred Drake03c44a32010-02-19 06:08:41 +00001162 def set(self, section, option, value=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001163 """Set an option. Extends RawConfigParser.set by validating type and
1164 interpolation syntax on the value."""
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001165 self._validate_value_types(option=option, value=value)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001166 super().set(section, option, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001167
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001168 def add_section(self, section):
1169 """Create a new section in the configuration. Extends
1170 RawConfigParser.add_section by validating if the section name is
1171 a string."""
1172 self._validate_value_types(section=section)
1173 super().add_section(section)
1174
Łukasz Langa26d513c2010-11-10 18:57:39 +00001175
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001176class SafeConfigParser(ConfigParser):
1177 """ConfigParser alias for backwards compatibility purposes."""
1178
1179 def __init__(self, *args, **kwargs):
1180 super().__init__(*args, **kwargs)
1181 warnings.warn(
1182 "The SafeConfigParser class has been renamed to ConfigParser "
1183 "in Python 3.2. This alias will be removed in future versions."
1184 " Use ConfigParser directly instead.",
1185 DeprecationWarning, stacklevel=2
1186 )
1187
1188
Łukasz Langa26d513c2010-11-10 18:57:39 +00001189class SectionProxy(MutableMapping):
1190 """A proxy for a single section from a parser."""
1191
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001192 def __init__(self, parser, name):
1193 """Creates a view on a section of the specified `name` in `parser`."""
Łukasz Langa26d513c2010-11-10 18:57:39 +00001194 self._parser = parser
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001195 self._name = name
Łukasz Langa26d513c2010-11-10 18:57:39 +00001196
1197 def __repr__(self):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001198 return '<Section: {}>'.format(self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001199
1200 def __getitem__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001201 if not self._parser.has_option(self._name, key):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001202 raise KeyError(key)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001203 return self._parser.get(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001204
1205 def __setitem__(self, key, value):
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001206 self._parser._validate_value_types(option=key, value=value)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001207 return self._parser.set(self._name, key, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001208
1209 def __delitem__(self, key):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001210 if not (self._parser.has_option(self._name, key) and
1211 self._parser.remove_option(self._name, key)):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001212 raise KeyError(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001213
1214 def __contains__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001215 return self._parser.has_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001216
1217 def __len__(self):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001218 return len(self._options())
Łukasz Langa26d513c2010-11-10 18:57:39 +00001219
1220 def __iter__(self):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001221 return self._options().__iter__()
1222
1223 def _options(self):
1224 if self._name != self._parser.default_section:
1225 return self._parser.options(self._name)
1226 else:
1227 return self._parser.defaults()
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001228
Łukasz Langa2f0fd0f2010-12-04 17:48:18 +00001229 def get(self, option, fallback=None, *, raw=False, vars=None):
1230 return self._parser.get(self._name, option, raw=raw, vars=vars,
1231 fallback=fallback)
1232
1233 def getint(self, option, fallback=None, *, raw=False, vars=None):
1234 return self._parser.getint(self._name, option, raw=raw, vars=vars,
1235 fallback=fallback)
1236
1237 def getfloat(self, option, fallback=None, *, raw=False, vars=None):
1238 return self._parser.getfloat(self._name, option, raw=raw, vars=vars,
1239 fallback=fallback)
1240
1241 def getboolean(self, option, fallback=None, *, raw=False, vars=None):
1242 return self._parser.getboolean(self._name, option, raw=raw, vars=vars,
1243 fallback=fallback)
1244
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001245 @property
1246 def parser(self):
1247 # The parser object of the proxy is read-only.
1248 return self._parser
1249
1250 @property
1251 def name(self):
1252 # The name of the section on a proxy is read-only.
1253 return self._name