blob: e5536a0024b97d7391b6af8898d13bf0f649cf1a [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 Hettingere6603602011-02-21 19:38:53 +0000121from collections import MutableMapping, OrderedDict as _default_dict, _ChainMap
Łukasz Langa26d513c2010-11-10 18:57:39 +0000122import functools
Fred Drakea4923622010-08-09 12:52:45 +0000123import io
Łukasz Langa26d513c2010-11-10 18:57:39 +0000124import itertools
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000125import re
Georg Brandl96a60ae2010-07-28 13:13:46 +0000126import sys
Fred Drakea4923622010-08-09 12:52:45 +0000127import warnings
Guido van Rossum3d209861997-12-09 16:10:31 +0000128
Fred Drakea4923622010-08-09 12:52:45 +0000129__all__ = ["NoSectionError", "DuplicateOptionError", "DuplicateSectionError",
130 "NoOptionError", "InterpolationError", "InterpolationDepthError",
Fred Drake8d5dd982002-12-30 23:51:45 +0000131 "InterpolationSyntaxError", "ParsingError",
David Goodger1cbf2062004-10-03 15:55:09 +0000132 "MissingSectionHeaderError",
133 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +0000134 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000135
Guido van Rossum3d209861997-12-09 16:10:31 +0000136DEFAULTSECT = "DEFAULT"
137
Fred Drake2a37f9f2000-09-27 22:43:54 +0000138MAX_INTERPOLATION_DEPTH = 10
139
Guido van Rossum3d209861997-12-09 16:10:31 +0000140
Tim Peters88869f92001-01-14 23:36:06 +0000141
Guido van Rossum3d209861997-12-09 16:10:31 +0000142# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000143class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000144 """Base class for ConfigParser exceptions."""
145
Guido van Rossum360e4b82007-05-14 22:51:27 +0000146 def _get_message(self):
147 """Getter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000148 BaseException.
149 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000150 return self.__message
151
152 def _set_message(self, value):
153 """Setter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000154 BaseException.
155 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000156 self.__message = value
157
158 # BaseException.message has been deprecated since Python 2.6. To prevent
Fred Drakea4923622010-08-09 12:52:45 +0000159 # DeprecationWarning from popping up over this pre-existing attribute, use
160 # a new property that takes lookup precedence.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000161 message = property(_get_message, _set_message)
162
Guido van Rossum3d209861997-12-09 16:10:31 +0000163 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000164 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000165 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000166
Guido van Rossum3d209861997-12-09 16:10:31 +0000167 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000168 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000169
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000170 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000171
Georg Brandl96a60ae2010-07-28 13:13:46 +0000172
Guido van Rossum3d209861997-12-09 16:10:31 +0000173class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000174 """Raised when no section matches a requested option."""
175
Guido van Rossum3d209861997-12-09 16:10:31 +0000176 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000177 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000178 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000179 self.args = (section, )
Guido van Rossum3d209861997-12-09 16:10:31 +0000180
Georg Brandl96a60ae2010-07-28 13:13:46 +0000181
Guido van Rossum3d209861997-12-09 16:10:31 +0000182class DuplicateSectionError(Error):
Fred Drakea4923622010-08-09 12:52:45 +0000183 """Raised when a section is repeated in an input source.
Fred Drake8d5dd982002-12-30 23:51:45 +0000184
Fred Drakea4923622010-08-09 12:52:45 +0000185 Possible repetitions that raise this exception are: multiple creation
186 using the API or in strict parsers when a section is found more than once
187 in a single input file, string or dictionary.
188 """
189
190 def __init__(self, section, source=None, lineno=None):
191 msg = [repr(section), " already exists"]
192 if source is not None:
193 message = ["While reading from ", source]
194 if lineno is not None:
195 message.append(" [line {0:2d}]".format(lineno))
196 message.append(": section ")
197 message.extend(msg)
198 msg = message
199 else:
200 msg.insert(0, "Section ")
201 Error.__init__(self, "".join(msg))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000202 self.section = section
Fred Drakea4923622010-08-09 12:52:45 +0000203 self.source = source
204 self.lineno = lineno
205 self.args = (section, source, lineno)
206
207
208class DuplicateOptionError(Error):
209 """Raised by strict parsers when an option is repeated in an input source.
210
211 Current implementation raises this exception only when an option is found
212 more than once in a single file, string or dictionary.
213 """
214
215 def __init__(self, section, option, source=None, lineno=None):
216 msg = [repr(option), " in section ", repr(section),
217 " already exists"]
218 if source is not None:
219 message = ["While reading from ", source]
220 if lineno is not None:
221 message.append(" [line {0:2d}]".format(lineno))
222 message.append(": option ")
223 message.extend(msg)
224 msg = message
225 else:
226 msg.insert(0, "Option ")
227 Error.__init__(self, "".join(msg))
228 self.section = section
229 self.option = option
230 self.source = source
231 self.lineno = lineno
232 self.args = (section, option, source, lineno)
Guido van Rossum3d209861997-12-09 16:10:31 +0000233
Georg Brandl96a60ae2010-07-28 13:13:46 +0000234
Guido van Rossum3d209861997-12-09 16:10:31 +0000235class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000236 """A requested option was not found."""
237
Guido van Rossum3d209861997-12-09 16:10:31 +0000238 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000239 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000240 (option, section))
241 self.option = option
242 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000243 self.args = (option, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000244
Georg Brandl96a60ae2010-07-28 13:13:46 +0000245
Guido van Rossum3d209861997-12-09 16:10:31 +0000246class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000247 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000248
Fred Drakee2c64912002-12-31 17:23:27 +0000249 def __init__(self, option, section, msg):
250 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000251 self.option = option
252 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000253 self.args = (option, section, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000254
Georg Brandl96a60ae2010-07-28 13:13:46 +0000255
Fred Drakee2c64912002-12-31 17:23:27 +0000256class InterpolationMissingOptionError(InterpolationError):
257 """A string substitution required a setting which was not available."""
258
259 def __init__(self, option, section, rawval, reference):
260 msg = ("Bad value substitution:\n"
261 "\tsection: [%s]\n"
262 "\toption : %s\n"
263 "\tkey : %s\n"
264 "\trawval : %s\n"
265 % (section, option, reference, rawval))
266 InterpolationError.__init__(self, option, section, msg)
267 self.reference = reference
Michael Foordbd6c0792010-07-25 23:09:25 +0000268 self.args = (option, section, rawval, reference)
Fred Drakee2c64912002-12-31 17:23:27 +0000269
Georg Brandl96a60ae2010-07-28 13:13:46 +0000270
Fred Drakee2c64912002-12-31 17:23:27 +0000271class InterpolationSyntaxError(InterpolationError):
Fred Drakea4923622010-08-09 12:52:45 +0000272 """Raised when the source text contains invalid syntax.
273
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000274 Current implementation raises this exception when the source text into
275 which substitutions are made does not conform to the required syntax.
Fred Drakea4923622010-08-09 12:52:45 +0000276 """
Neal Norwitzce1d9442002-12-30 23:38:47 +0000277
Georg Brandl96a60ae2010-07-28 13:13:46 +0000278
Fred Drakee2c64912002-12-31 17:23:27 +0000279class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000280 """Raised when substitutions are nested too deeply."""
281
Fred Drake2a37f9f2000-09-27 22:43:54 +0000282 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000283 msg = ("Value interpolation too deeply recursive:\n"
284 "\tsection: [%s]\n"
285 "\toption : %s\n"
286 "\trawval : %s\n"
287 % (section, option, rawval))
288 InterpolationError.__init__(self, option, section, msg)
Michael Foordbd6c0792010-07-25 23:09:25 +0000289 self.args = (option, section, rawval)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000290
Georg Brandl96a60ae2010-07-28 13:13:46 +0000291
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000292class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000293 """Raised when a configuration file does not follow legal syntax."""
294
Fred Drakea4923622010-08-09 12:52:45 +0000295 def __init__(self, source=None, filename=None):
296 # Exactly one of `source'/`filename' arguments has to be given.
297 # `filename' kept for compatibility.
298 if filename and source:
299 raise ValueError("Cannot specify both `filename' and `source'. "
300 "Use `source'.")
301 elif not filename and not source:
302 raise ValueError("Required argument `source' not given.")
303 elif filename:
304 source = filename
305 Error.__init__(self, 'Source contains parsing errors: %s' % source)
306 self.source = source
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000307 self.errors = []
Fred Drakea4923622010-08-09 12:52:45 +0000308 self.args = (source, )
309
310 @property
311 def filename(self):
312 """Deprecated, use `source'."""
313 warnings.warn(
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000314 "The 'filename' attribute will be removed in future versions. "
Fred Drakea4923622010-08-09 12:52:45 +0000315 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000316 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000317 )
318 return self.source
319
320 @filename.setter
321 def filename(self, value):
322 """Deprecated, user `source'."""
323 warnings.warn(
324 "The 'filename' attribute will be removed in future versions. "
325 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000326 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000327 )
328 self.source = value
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000329
330 def append(self, lineno, line):
331 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000332 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000333
Georg Brandl96a60ae2010-07-28 13:13:46 +0000334
Fred Drake2a37f9f2000-09-27 22:43:54 +0000335class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000336 """Raised when a key-value pair is found before any section header."""
337
Fred Drake2a37f9f2000-09-27 22:43:54 +0000338 def __init__(self, filename, lineno, line):
339 Error.__init__(
340 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000341 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000342 (filename, lineno, line))
Fred Drakea4923622010-08-09 12:52:45 +0000343 self.source = filename
Fred Drake2a37f9f2000-09-27 22:43:54 +0000344 self.lineno = lineno
345 self.line = line
Michael Foordbd6c0792010-07-25 23:09:25 +0000346 self.args = (filename, lineno, line)
Guido van Rossum3d209861997-12-09 16:10:31 +0000347
Georg Brandl96a60ae2010-07-28 13:13:46 +0000348
Fred Drakecc645b92010-09-04 04:35:34 +0000349# Used in parser getters to indicate the default behaviour when a specific
350# option is not found it to raise an exception. Created to enable `None' as
351# a valid fallback value.
352_UNSET = object()
353
354
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000355class Interpolation:
356 """Dummy interpolation that passes the value through with no changes."""
357
358 def before_get(self, parser, section, option, value, defaults):
359 return value
360
361 def before_set(self, parser, section, option, value):
362 return value
363
364 def before_read(self, parser, section, option, value):
365 return value
366
367 def before_write(self, parser, section, option, value):
368 return value
369
370
371class BasicInterpolation(Interpolation):
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000372 """Interpolation as implemented in the classic ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000373
374 The option values can contain format strings which refer to other values in
375 the same section, or values in the special default section.
376
377 For example:
378
379 something: %(dir)s/whatever
380
381 would resolve the "%(dir)s" to the value of dir. All reference
382 expansions are done late, on demand. If a user needs to use a bare % in
Ezio Melottie130a522011-10-19 10:58:56 +0300383 a configuration file, she can escape it by writing %%. Other % usage
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000384 is considered a user error and raises `InterpolationSyntaxError'."""
385
386 _KEYCRE = re.compile(r"%\(([^)]+)\)s")
387
388 def before_get(self, parser, section, option, value, defaults):
389 L = []
390 self._interpolate_some(parser, option, L, value, section, defaults, 1)
391 return ''.join(L)
392
393 def before_set(self, parser, section, option, value):
394 tmp_value = value.replace('%%', '') # escaped percent signs
395 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
396 if '%' in tmp_value:
397 raise ValueError("invalid interpolation syntax in %r at "
398 "position %d" % (value, tmp_value.find('%')))
399 return value
400
401 def _interpolate_some(self, parser, option, accum, rest, section, map,
402 depth):
403 if depth > MAX_INTERPOLATION_DEPTH:
404 raise InterpolationDepthError(option, section, rest)
405 while rest:
406 p = rest.find("%")
407 if p < 0:
408 accum.append(rest)
409 return
410 if p > 0:
411 accum.append(rest[:p])
412 rest = rest[p:]
413 # p is no longer used
414 c = rest[1:2]
415 if c == "%":
416 accum.append("%")
417 rest = rest[2:]
418 elif c == "(":
419 m = self._KEYCRE.match(rest)
420 if m is None:
421 raise InterpolationSyntaxError(option, section,
422 "bad interpolation variable reference %r" % rest)
423 var = parser.optionxform(m.group(1))
424 rest = rest[m.end():]
425 try:
426 v = map[var]
427 except KeyError:
428 raise InterpolationMissingOptionError(
429 option, section, rest, var)
430 if "%" in v:
431 self._interpolate_some(parser, option, accum, v,
432 section, map, depth + 1)
433 else:
434 accum.append(v)
435 else:
436 raise InterpolationSyntaxError(
437 option, section,
438 "'%%' must be followed by '%%' or '(', "
439 "found: %r" % (rest,))
440
441
442class ExtendedInterpolation(Interpolation):
443 """Advanced variant of interpolation, supports the syntax used by
444 `zc.buildout'. Enables interpolation between sections."""
445
446 _KEYCRE = re.compile(r"\$\{([^}]+)\}")
447
448 def before_get(self, parser, section, option, value, defaults):
449 L = []
450 self._interpolate_some(parser, option, L, value, section, defaults, 1)
451 return ''.join(L)
452
453 def before_set(self, parser, section, option, value):
454 tmp_value = value.replace('$$', '') # escaped dollar signs
455 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
456 if '$' in tmp_value:
457 raise ValueError("invalid interpolation syntax in %r at "
458 "position %d" % (value, tmp_value.find('%')))
459 return value
460
461 def _interpolate_some(self, parser, option, accum, rest, section, map,
462 depth):
463 if depth > MAX_INTERPOLATION_DEPTH:
464 raise InterpolationDepthError(option, section, rest)
465 while rest:
466 p = rest.find("$")
467 if p < 0:
468 accum.append(rest)
469 return
470 if p > 0:
471 accum.append(rest[:p])
472 rest = rest[p:]
473 # p is no longer used
474 c = rest[1:2]
475 if c == "$":
476 accum.append("$")
477 rest = rest[2:]
478 elif c == "{":
479 m = self._KEYCRE.match(rest)
480 if m is None:
481 raise InterpolationSyntaxError(option, section,
482 "bad interpolation variable reference %r" % rest)
Łukasz Langae698cd52011-04-28 10:58:57 +0200483 path = m.group(1).split(':')
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000484 rest = rest[m.end():]
485 sect = section
486 opt = option
487 try:
488 if len(path) == 1:
Łukasz Langae698cd52011-04-28 10:58:57 +0200489 opt = parser.optionxform(path[0])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000490 v = map[opt]
491 elif len(path) == 2:
492 sect = path[0]
Łukasz Langae698cd52011-04-28 10:58:57 +0200493 opt = parser.optionxform(path[1])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000494 v = parser.get(sect, opt, raw=True)
495 else:
496 raise InterpolationSyntaxError(
497 option, section,
498 "More than one ':' found: %r" % (rest,))
Łukasz Langa71b37a52010-12-17 21:56:32 +0000499 except (KeyError, NoSectionError, NoOptionError):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000500 raise InterpolationMissingOptionError(
Łukasz Langa71b37a52010-12-17 21:56:32 +0000501 option, section, rest, ":".join(path))
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000502 if "$" in v:
503 self._interpolate_some(parser, opt, accum, v, sect,
504 dict(parser.items(sect, raw=True)),
505 depth + 1)
506 else:
507 accum.append(v)
508 else:
509 raise InterpolationSyntaxError(
510 option, section,
511 "'$' must be followed by '$' or '{', "
512 "found: %r" % (rest,))
513
514
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000515class LegacyInterpolation(Interpolation):
516 """Deprecated interpolation used in old versions of ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000517 Use BasicInterpolation or ExtendedInterpolation instead."""
518
519 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
520
521 def before_get(self, parser, section, option, value, vars):
522 rawval = value
523 depth = MAX_INTERPOLATION_DEPTH
524 while depth: # Loop through this until it's done
525 depth -= 1
526 if value and "%(" in value:
527 replace = functools.partial(self._interpolation_replace,
528 parser=parser)
529 value = self._KEYCRE.sub(replace, value)
530 try:
531 value = value % vars
532 except KeyError as e:
533 raise InterpolationMissingOptionError(
534 option, section, rawval, e.args[0])
535 else:
536 break
537 if value and "%(" in value:
538 raise InterpolationDepthError(option, section, rawval)
539 return value
540
541 def before_set(self, parser, section, option, value):
542 return value
543
544 @staticmethod
545 def _interpolation_replace(match, parser):
546 s = match.group(1)
547 if s is None:
548 return match.group()
549 else:
550 return "%%(%s)s" % parser.optionxform(s)
551
552
Łukasz Langa26d513c2010-11-10 18:57:39 +0000553class RawConfigParser(MutableMapping):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000554 """ConfigParser that does not do interpolation."""
555
556 # Regular expressions for parsing section headers and options
557 _SECT_TMPL = r"""
558 \[ # [
559 (?P<header>[^]]+) # very permissive!
560 \] # ]
561 """
562 _OPT_TMPL = r"""
563 (?P<option>.*?) # very permissive!
564 \s*(?P<vi>{delim})\s* # any number of space/tab,
565 # followed by any of the
566 # allowed delimiters,
567 # followed by any space/tab
568 (?P<value>.*)$ # everything up to eol
569 """
570 _OPT_NV_TMPL = r"""
571 (?P<option>.*?) # very permissive!
572 \s*(?: # any number of space/tab,
573 (?P<vi>{delim})\s* # optionally followed by
574 # any of the allowed
575 # delimiters, followed by any
576 # space/tab
577 (?P<value>.*))?$ # everything up to eol
578 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000579 # Interpolation algorithm to be used if the user does not specify another
580 _DEFAULT_INTERPOLATION = Interpolation()
Georg Brandl96a60ae2010-07-28 13:13:46 +0000581 # Compiled regular expression for matching sections
582 SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
583 # Compiled regular expression for matching options with typical separators
584 OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
585 # Compiled regular expression for matching options with optional values
586 # delimited using typical separators
587 OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
588 # Compiled regular expression for matching leading whitespace in a line
589 NONSPACECRE = re.compile(r"\S")
Fred Drakecc645b92010-09-04 04:35:34 +0000590 # Possible boolean values in the configuration.
591 BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
592 '0': False, 'no': False, 'false': False, 'off': False}
Georg Brandl96a60ae2010-07-28 13:13:46 +0000593
Fred Drake03c44a32010-02-19 06:08:41 +0000594 def __init__(self, defaults=None, dict_type=_default_dict,
Fred Drakea4923622010-08-09 12:52:45 +0000595 allow_no_value=False, *, delimiters=('=', ':'),
Łukasz Langab25a7912010-12-17 01:32:29 +0000596 comment_prefixes=('#', ';'), inline_comment_prefixes=None,
597 strict=True, empty_lines_in_values=True,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000598 default_section=DEFAULTSECT,
599 interpolation=_UNSET):
600
Thomas Wouters89f507f2006-12-13 04:49:30 +0000601 self._dict = dict_type
602 self._sections = self._dict()
603 self._defaults = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000604 self._proxies = self._dict()
Łukasz Langac264c092010-11-20 16:15:37 +0000605 self._proxies[default_section] = SectionProxy(self, default_section)
David Goodger68a1abd2004-10-03 15:40:25 +0000606 if defaults:
607 for key, value in defaults.items():
608 self._defaults[self.optionxform(key)] = value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000609 self._delimiters = tuple(delimiters)
610 if delimiters == ('=', ':'):
611 self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
612 else:
Fred Drakea4923622010-08-09 12:52:45 +0000613 d = "|".join(re.escape(d) for d in delimiters)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000614 if allow_no_value:
Fred Drakea4923622010-08-09 12:52:45 +0000615 self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000616 re.VERBOSE)
617 else:
Fred Drakea4923622010-08-09 12:52:45 +0000618 self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000619 re.VERBOSE)
Łukasz Langab25a7912010-12-17 01:32:29 +0000620 self._comment_prefixes = tuple(comment_prefixes or ())
621 self._inline_comment_prefixes = tuple(inline_comment_prefixes or ())
Fred Drakea4923622010-08-09 12:52:45 +0000622 self._strict = strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000623 self._allow_no_value = allow_no_value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000624 self._empty_lines_in_values = empty_lines_in_values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000625 self.default_section=default_section
Łukasz Langa1aa422f2011-04-28 17:03:45 +0200626 self._interpolation = interpolation
627 if self._interpolation is _UNSET:
628 self._interpolation = self._DEFAULT_INTERPOLATION
629 if self._interpolation is None:
630 self._interpolation = Interpolation()
Guido van Rossum3d209861997-12-09 16:10:31 +0000631
632 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000633 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000634
635 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000636 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000637 # self._sections will never have [DEFAULT] in it
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000638 return list(self._sections.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000639
640 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000641 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000642
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000643 Raise DuplicateSectionError if a section by the specified name
Łukasz Langac264c092010-11-20 16:15:37 +0000644 already exists. Raise ValueError if name is DEFAULT.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000645 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000646 if section == self.default_section:
Łukasz Langa3a11e712010-12-03 22:15:19 +0000647 raise ValueError('Invalid section name: %r' % section)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000648
Fred Drakefce65572002-10-25 18:08:18 +0000649 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000650 raise DuplicateSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000651 self._sections[section] = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000652 self._proxies[section] = SectionProxy(self, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000653
654 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000655 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000656
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000657 The DEFAULT section is not acknowledged.
658 """
Fred Drakefce65572002-10-25 18:08:18 +0000659 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000660
661 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000662 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000663 try:
Fred Drakefce65572002-10-25 18:08:18 +0000664 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000665 except KeyError:
666 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000667 opts.update(self._defaults)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000668 return list(opts.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000669
Georg Brandl8dcaa732010-07-29 12:17:40 +0000670 def read(self, filenames, encoding=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000671 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000672
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000673 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000674 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000675 configuration file locations (e.g. current directory, user's
676 home directory, systemwide directory), and all existing
677 configuration files in the list will be read. A single
678 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000679
680 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000681 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000682 if isinstance(filenames, str):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000683 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000684 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000685 for filename in filenames:
686 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000687 with open(filename, encoding=encoding) as fp:
688 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000689 except IOError:
690 continue
Fred Drake82903142004-05-18 04:24:02 +0000691 read_ok.append(filename)
692 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000693
Fred Drakea4923622010-08-09 12:52:45 +0000694 def read_file(self, f, source=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000695 """Like read() but the argument must be a file-like object.
696
Łukasz Langadaab1c82011-04-27 18:10:05 +0200697 The `f' argument must be iterable, returning one line at a time.
698 Optional second argument is the `source' specifying the name of the
699 file being read. If not given, it is taken from f.name. If `f' has no
700 `name' attribute, `<???>' is used.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000701 """
Fred Drakea4923622010-08-09 12:52:45 +0000702 if source is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000703 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000704 source = f.name
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000705 except AttributeError:
Fred Drakea4923622010-08-09 12:52:45 +0000706 source = '<???>'
707 self._read(f, source)
708
709 def read_string(self, string, source='<string>'):
710 """Read configuration from a given string."""
711 sfile = io.StringIO(string)
712 self.read_file(sfile, source)
713
714 def read_dict(self, dictionary, source='<dict>'):
715 """Read configuration from a dictionary.
716
717 Keys are section names, values are dictionaries with keys and values
718 that should be present in the section. If the used dictionary type
719 preserves order, sections and their keys will be added in order.
720
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000721 All types held in the dictionary are converted to strings during
722 reading, including section names, option names and keys.
723
Fred Drakea4923622010-08-09 12:52:45 +0000724 Optional second argument is the `source' specifying the name of the
725 dictionary being read.
726 """
727 elements_added = set()
728 for section, keys in dictionary.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000729 section = str(section)
Fred Drakea4923622010-08-09 12:52:45 +0000730 try:
731 self.add_section(section)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000732 except (DuplicateSectionError, ValueError):
Fred Drakea4923622010-08-09 12:52:45 +0000733 if self._strict and section in elements_added:
734 raise
Łukasz Langa71b37a52010-12-17 21:56:32 +0000735 elements_added.add(section)
Fred Drakea4923622010-08-09 12:52:45 +0000736 for key, value in keys.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000737 key = self.optionxform(str(key))
Fred Drakecc645b92010-09-04 04:35:34 +0000738 if value is not None:
739 value = str(value)
Fred Drakea4923622010-08-09 12:52:45 +0000740 if self._strict and (section, key) in elements_added:
741 raise DuplicateOptionError(section, key, source)
742 elements_added.add((section, key))
743 self.set(section, key, value)
744
745 def readfp(self, fp, filename=None):
746 """Deprecated, use read_file instead."""
747 warnings.warn(
748 "This method will be removed in future versions. "
749 "Use 'parser.read_file()' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000750 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000751 )
752 self.read_file(fp, source=filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000753
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000754 def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000755 """Get an option value for a given section.
756
757 If `vars' is provided, it must be a dictionary. The option is looked up
758 in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000759 If the key is not found and `fallback' is provided, it is used as
760 a fallback value. `None' can be provided as a `fallback' value.
761
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000762 If interpolation is enabled and the optional argument `raw' is False,
763 all interpolations are expanded in the return values.
764
765 Arguments `raw', `vars', and `fallback' are keyword only.
766
767 The section DEFAULT is special.
Fred Drakecc645b92010-09-04 04:35:34 +0000768 """
769 try:
770 d = self._unify_values(section, vars)
771 except NoSectionError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000772 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000773 raise
Fred Drakefce65572002-10-25 18:08:18 +0000774 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000775 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000776 option = self.optionxform(option)
777 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000778 value = d[option]
Fred Drakecc645b92010-09-04 04:35:34 +0000779 except KeyError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000780 if fallback is _UNSET:
Fred Drakefce65572002-10-25 18:08:18 +0000781 raise NoOptionError(option, section)
Fred Drakecc645b92010-09-04 04:35:34 +0000782 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000783 return fallback
Fred Drake2a37f9f2000-09-27 22:43:54 +0000784
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000785 if raw or value is None:
786 return value
787 else:
788 return self._interpolation.before_get(self, section, option, value,
789 d)
Fred Drake2ca041f2002-09-27 15:49:56 +0000790
Łukasz Langa26d513c2010-11-10 18:57:39 +0000791 def _get(self, section, conv, option, **kwargs):
792 return conv(self.get(section, option, **kwargs))
Guido van Rossum3d209861997-12-09 16:10:31 +0000793
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000794 def getint(self, section, option, *, raw=False, vars=None,
795 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000796 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000797 return self._get(section, int, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000798 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000799 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000800 raise
801 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000802 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000803
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000804 def getfloat(self, section, option, *, raw=False, vars=None,
805 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000806 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000807 return self._get(section, float, option, raw=raw, vars=vars)
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
811 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000812 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000813
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000814 def getboolean(self, section, option, *, raw=False, vars=None,
815 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000816 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000817 return self._get(section, self._convert_to_boolean, option,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000818 raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000819 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000820 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000821 raise
822 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000823 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000824
Łukasz Langa71b37a52010-12-17 21:56:32 +0000825 def items(self, section=_UNSET, raw=False, vars=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000826 """Return a list of (name, value) tuples for each option in a section.
827
828 All % interpolations are expanded in the return values, based on the
829 defaults passed into the constructor, unless the optional argument
830 `raw' is true. Additional substitutions may be provided using the
831 `vars' argument, which must be a dictionary whose contents overrides
832 any pre-existing defaults.
833
834 The section DEFAULT is special.
835 """
Łukasz Langa71b37a52010-12-17 21:56:32 +0000836 if section is _UNSET:
837 return super().items()
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000838 d = self._defaults.copy()
839 try:
840 d.update(self._sections[section])
841 except KeyError:
842 if section != self.default_section:
843 raise NoSectionError(section)
844 # Update with the entry specific variables
845 if vars:
846 for key, value in vars.items():
847 d[self.optionxform(key)] = value
Łukasz Langa24bcc612010-12-04 11:48:11 +0000848 value_getter = lambda option: self._interpolation.before_get(self,
849 section, option, d[option], d)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000850 if raw:
Łukasz Langa24bcc612010-12-04 11:48:11 +0000851 value_getter = lambda option: d[option]
852 return [(option, value_getter(option)) for option in d.keys()]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000853
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100854 def popitem(self):
855 """Remove a section from the parser and return it as
856 a (section_name, section_proxy) tuple. If no section is present, raise
857 KeyError.
858
859 The section DEFAULT is never returned because it cannot be removed.
860 """
861 for key in self.sections():
862 value = self[key]
863 del self[key]
864 return key, value
865 raise KeyError
866
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000867 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000868 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000869
Eric S. Raymond417c4892000-07-10 18:11:00 +0000870 def has_option(self, section, option):
Łukasz Langa71b37a52010-12-17 21:56:32 +0000871 """Check for the existence of a given option in a given section.
872 If the specified `section' is None or an empty string, DEFAULT is
873 assumed. If the specified `section' does not exist, returns False."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000874 if not section or section == self.default_section:
Fred Drakec2ff9052002-09-27 15:33:11 +0000875 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000876 return option in self._defaults
877 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000878 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000879 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000880 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000881 return (option in self._sections[section]
882 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000883
Fred Drake03c44a32010-02-19 06:08:41 +0000884 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000885 """Set an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000886 if value:
887 value = self._interpolation.before_set(self, section, option,
888 value)
889 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000890 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000891 else:
892 try:
Fred Drakefce65572002-10-25 18:08:18 +0000893 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000894 except KeyError:
895 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000896 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000897
Georg Brandl96a60ae2010-07-28 13:13:46 +0000898 def write(self, fp, space_around_delimiters=True):
899 """Write an .ini-format representation of the configuration state.
900
901 If `space_around_delimiters' is True (the default), delimiters
902 between keys and values are surrounded by spaces.
903 """
904 if space_around_delimiters:
905 d = " {} ".format(self._delimiters[0])
906 else:
907 d = self._delimiters[0]
Fred Drakefce65572002-10-25 18:08:18 +0000908 if self._defaults:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000909 self._write_section(fp, self.default_section,
Łukasz Langac264c092010-11-20 16:15:37 +0000910 self._defaults.items(), d)
Fred Drakefce65572002-10-25 18:08:18 +0000911 for section in self._sections:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000912 self._write_section(fp, section,
913 self._sections[section].items(), d)
914
915 def _write_section(self, fp, section_name, section_items, delimiter):
916 """Write a single section to the specified `fp'."""
917 fp.write("[{}]\n".format(section_name))
918 for key, value in section_items:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000919 value = self._interpolation.before_write(self, section_name, key,
920 value)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000921 if value is not None or not self._allow_no_value:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000922 value = delimiter + str(value).replace('\n', '\n\t')
923 else:
924 value = ""
925 fp.write("{}{}\n".format(key, value))
926 fp.write("\n")
Eric S. Raymond417c4892000-07-10 18:11:00 +0000927
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000928 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000929 """Remove an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000930 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000931 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000932 else:
933 try:
Fred Drakefce65572002-10-25 18:08:18 +0000934 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000935 except KeyError:
936 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000937 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000938 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000939 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000940 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000941 return existed
942
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000943 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000944 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000945 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000946 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000947 del self._sections[section]
Łukasz Langa49afa382010-11-11 19:53:23 +0000948 del self._proxies[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000949 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000950
Łukasz Langa26d513c2010-11-10 18:57:39 +0000951 def __getitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000952 if key != self.default_section and not self.has_section(key):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000953 raise KeyError(key)
Łukasz Langa49afa382010-11-11 19:53:23 +0000954 return self._proxies[key]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000955
956 def __setitem__(self, key, value):
957 # To conform with the mapping protocol, overwrites existing values in
958 # the section.
959
960 # XXX this is not atomic if read_dict fails at any point. Then again,
961 # no update method in configparser is atomic in this implementation.
Łukasz Langaa2e7acd2013-01-01 23:45:33 +0100962 if key in self._sections:
963 self._sections[key].clear()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000964 self.read_dict({key: value})
965
966 def __delitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000967 if key == self.default_section:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000968 raise ValueError("Cannot remove the default section.")
969 if not self.has_section(key):
970 raise KeyError(key)
971 self.remove_section(key)
972
973 def __contains__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000974 return key == self.default_section or self.has_section(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000975
976 def __len__(self):
977 return len(self._sections) + 1 # the default section
978
979 def __iter__(self):
980 # XXX does it break when underlying container state changed?
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000981 return itertools.chain((self.default_section,), self._sections.keys())
Łukasz Langa26d513c2010-11-10 18:57:39 +0000982
Fred Drakefce65572002-10-25 18:08:18 +0000983 def _read(self, fp, fpname):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000984 """Parse a sectioned configuration file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000985
Fred Drakea4923622010-08-09 12:52:45 +0000986 Each section in a configuration file contains a header, indicated by
987 a name in square brackets (`[]'), plus key/value options, indicated by
Georg Brandl96a60ae2010-07-28 13:13:46 +0000988 `name' and `value' delimited with a specific substring (`=' or `:' by
989 default).
990
Fred Drakea4923622010-08-09 12:52:45 +0000991 Values can span multiple lines, as long as they are indented deeper
992 than the first line of the value. Depending on the parser's mode, blank
993 lines may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000994
995 Configuration files may include comments, prefixed by specific
Fred Drakea4923622010-08-09 12:52:45 +0000996 characters (`#' and `;' by default). Comments may appear on their own
997 in an otherwise empty line or may be entered in lines holding values or
Georg Brandl96a60ae2010-07-28 13:13:46 +0000998 section names.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000999 """
Fred Drakea4923622010-08-09 12:52:45 +00001000 elements_added = set()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001001 cursect = None # None, or a dictionary
Fred Drakea4923622010-08-09 12:52:45 +00001002 sectname = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001003 optname = None
1004 lineno = 0
Georg Brandl96a60ae2010-07-28 13:13:46 +00001005 indent_level = 0
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001006 e = None # None, or an exception
Georg Brandl96a60ae2010-07-28 13:13:46 +00001007 for lineno, line in enumerate(fp, start=1):
Georg Brandl96a60ae2010-07-28 13:13:46 +00001008 comment_start = None
Georg Brandl96a60ae2010-07-28 13:13:46 +00001009 # strip inline comments
Łukasz Langab25a7912010-12-17 01:32:29 +00001010 for prefix in self._inline_comment_prefixes:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001011 index = line.find(prefix)
1012 if index == 0 or (index > 0 and line[index-1].isspace()):
1013 comment_start = index
1014 break
Łukasz Langab25a7912010-12-17 01:32:29 +00001015 # strip full line comments
1016 for prefix in self._comment_prefixes:
1017 if line.strip().startswith(prefix):
1018 comment_start = 0
1019 break
Georg Brandl96a60ae2010-07-28 13:13:46 +00001020 value = line[:comment_start].strip()
1021 if not value:
Georg Brandlf206d0e2010-07-29 11:56:20 +00001022 if self._empty_lines_in_values:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001023 # add empty line to the value, but only if there was no
1024 # comment on the line
Georg Brandlf206d0e2010-07-29 11:56:20 +00001025 if (comment_start is None and
1026 cursect is not None and
1027 optname and
1028 cursect[optname] is not None):
1029 cursect[optname].append('') # newlines added at join
Georg Brandl96a60ae2010-07-28 13:13:46 +00001030 else:
1031 # empty line marks end of value
1032 indent_level = sys.maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001033 continue
1034 # continuation line?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001035 first_nonspace = self.NONSPACECRE.search(line)
1036 cur_indent_level = first_nonspace.start() if first_nonspace else 0
1037 if (cursect is not None and optname and
1038 cur_indent_level > indent_level):
1039 cursect[optname].append(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001040 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001041 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001042 indent_level = cur_indent_level
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001043 # is it a section header?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001044 mo = self.SECTCRE.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001045 if mo:
1046 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +00001047 if sectname in self._sections:
Fred Drakea4923622010-08-09 12:52:45 +00001048 if self._strict and sectname in elements_added:
1049 raise DuplicateSectionError(sectname, fpname,
1050 lineno)
Fred Drakefce65572002-10-25 18:08:18 +00001051 cursect = self._sections[sectname]
Fred Drakea4923622010-08-09 12:52:45 +00001052 elements_added.add(sectname)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001053 elif sectname == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001054 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001055 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001056 cursect = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +00001057 self._sections[sectname] = cursect
Łukasz Langa49afa382010-11-11 19:53:23 +00001058 self._proxies[sectname] = SectionProxy(self, sectname)
Fred Drakea4923622010-08-09 12:52:45 +00001059 elements_added.add(sectname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001060 # So sections can't start with a continuation line
1061 optname = None
1062 # no section header in the file?
1063 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001064 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001065 # an option line?
1066 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001067 mo = self._optcre.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001068 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +00001069 optname, vi, optval = mo.group('option', 'vi', 'value')
Georg Brandl96a60ae2010-07-28 13:13:46 +00001070 if not optname:
1071 e = self._handle_error(e, fpname, lineno, line)
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001072 optname = self.optionxform(optname.rstrip())
Fred Drakea4923622010-08-09 12:52:45 +00001073 if (self._strict and
1074 (sectname, optname) in elements_added):
1075 raise DuplicateOptionError(sectname, optname,
1076 fpname, lineno)
1077 elements_added.add((sectname, optname))
Fred Drake03c44a32010-02-19 06:08:41 +00001078 # This check is fine because the OPTCRE cannot
1079 # match if it would set optval to None
1080 if optval is not None:
Fred Drake03c44a32010-02-19 06:08:41 +00001081 optval = optval.strip()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001082 cursect[optname] = [optval]
1083 else:
1084 # valueless option handling
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001085 cursect[optname] = None
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001086 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001087 # a non-fatal parsing error occurred. set up the
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001088 # exception but keep going. the exception will be
1089 # raised at the end of the file and will contain a
1090 # list of all bogus lines
Georg Brandl96a60ae2010-07-28 13:13:46 +00001091 e = self._handle_error(e, fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001092 # if any parsing errors occurred, raise an exception
1093 if e:
1094 raise e
Georg Brandl96a60ae2010-07-28 13:13:46 +00001095 self._join_multiline_values()
Fred Drakefce65572002-10-25 18:08:18 +00001096
Georg Brandl96a60ae2010-07-28 13:13:46 +00001097 def _join_multiline_values(self):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001098 defaults = self.default_section, self._defaults
1099 all_sections = itertools.chain((defaults,),
1100 self._sections.items())
1101 for section, options in all_sections:
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001102 for name, val in options.items():
1103 if isinstance(val, list):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001104 val = '\n'.join(val).rstrip()
1105 options[name] = self._interpolation.before_read(self,
1106 section,
1107 name, val)
Fred Drakefce65572002-10-25 18:08:18 +00001108
Georg Brandl96a60ae2010-07-28 13:13:46 +00001109 def _handle_error(self, exc, fpname, lineno, line):
1110 if not exc:
1111 exc = ParsingError(fpname)
1112 exc.append(lineno, repr(line))
1113 return exc
1114
Fred Drakecc645b92010-09-04 04:35:34 +00001115 def _unify_values(self, section, vars):
Raymond Hettingere6603602011-02-21 19:38:53 +00001116 """Create a sequence of lookups with 'vars' taking priority over
1117 the 'section' which takes priority over the DEFAULTSECT.
1118
Fred Drakefce65572002-10-25 18:08:18 +00001119 """
Raymond Hettingere6603602011-02-21 19:38:53 +00001120 sectiondict = {}
Fred Drakefce65572002-10-25 18:08:18 +00001121 try:
Raymond Hettingere6603602011-02-21 19:38:53 +00001122 sectiondict = self._sections[section]
Fred Drakefce65572002-10-25 18:08:18 +00001123 except KeyError:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001124 if section != self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001125 raise NoSectionError(section)
1126 # Update with the entry specific variables
Raymond Hettingere6603602011-02-21 19:38:53 +00001127 vardict = {}
David Goodger68a1abd2004-10-03 15:40:25 +00001128 if vars:
1129 for key, value in vars.items():
Fred Drakecc645b92010-09-04 04:35:34 +00001130 if value is not None:
1131 value = str(value)
Raymond Hettingere6603602011-02-21 19:38:53 +00001132 vardict[self.optionxform(key)] = value
1133 return _ChainMap(vardict, sectiondict, self._defaults)
Fred Drakecc645b92010-09-04 04:35:34 +00001134
1135 def _convert_to_boolean(self, value):
1136 """Return a boolean value translating from other types if necessary.
1137 """
1138 if value.lower() not in self.BOOLEAN_STATES:
1139 raise ValueError('Not a boolean: %s' % value)
1140 return self.BOOLEAN_STATES[value.lower()]
1141
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001142 def _validate_value_types(self, *, section="", option="", value=""):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001143 """Raises a TypeError for non-string values.
1144
1145 The only legal non-string value if we allow valueless
1146 options is None, so we need to check if the value is a
1147 string if:
1148 - we do not allow valueless options, or
1149 - we allow valueless options but the value is not None
1150
1151 For compatibility reasons this method is not used in classic set()
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001152 for RawConfigParsers. It is invoked in every case for mapping protocol
1153 access and in ConfigParser.set().
Łukasz Langa26d513c2010-11-10 18:57:39 +00001154 """
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001155 if not isinstance(section, str):
1156 raise TypeError("section names must be strings")
1157 if not isinstance(option, str):
1158 raise TypeError("option keys must be strings")
Łukasz Langa26d513c2010-11-10 18:57:39 +00001159 if not self._allow_no_value or value:
1160 if not isinstance(value, str):
1161 raise TypeError("option values must be strings")
1162
1163
Fred Drakecc645b92010-09-04 04:35:34 +00001164class ConfigParser(RawConfigParser):
1165 """ConfigParser implementing interpolation."""
1166
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001167 _DEFAULT_INTERPOLATION = BasicInterpolation()
David Goodger1cbf2062004-10-03 15:55:09 +00001168
Fred Drake03c44a32010-02-19 06:08:41 +00001169 def set(self, section, option, value=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001170 """Set an option. Extends RawConfigParser.set by validating type and
1171 interpolation syntax on the value."""
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001172 self._validate_value_types(option=option, value=value)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001173 super().set(section, option, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001174
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001175 def add_section(self, section):
1176 """Create a new section in the configuration. Extends
1177 RawConfigParser.add_section by validating if the section name is
1178 a string."""
1179 self._validate_value_types(section=section)
1180 super().add_section(section)
1181
Łukasz Langa26d513c2010-11-10 18:57:39 +00001182
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001183class SafeConfigParser(ConfigParser):
1184 """ConfigParser alias for backwards compatibility purposes."""
1185
1186 def __init__(self, *args, **kwargs):
1187 super().__init__(*args, **kwargs)
1188 warnings.warn(
1189 "The SafeConfigParser class has been renamed to ConfigParser "
1190 "in Python 3.2. This alias will be removed in future versions."
1191 " Use ConfigParser directly instead.",
1192 DeprecationWarning, stacklevel=2
1193 )
1194
1195
Łukasz Langa26d513c2010-11-10 18:57:39 +00001196class SectionProxy(MutableMapping):
1197 """A proxy for a single section from a parser."""
1198
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001199 def __init__(self, parser, name):
1200 """Creates a view on a section of the specified `name` in `parser`."""
Łukasz Langa26d513c2010-11-10 18:57:39 +00001201 self._parser = parser
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001202 self._name = name
Łukasz Langa26d513c2010-11-10 18:57:39 +00001203
1204 def __repr__(self):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001205 return '<Section: {}>'.format(self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001206
1207 def __getitem__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001208 if not self._parser.has_option(self._name, key):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001209 raise KeyError(key)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001210 return self._parser.get(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001211
1212 def __setitem__(self, key, value):
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001213 self._parser._validate_value_types(option=key, value=value)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001214 return self._parser.set(self._name, key, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001215
1216 def __delitem__(self, key):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001217 if not (self._parser.has_option(self._name, key) and
1218 self._parser.remove_option(self._name, key)):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001219 raise KeyError(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001220
1221 def __contains__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001222 return self._parser.has_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001223
1224 def __len__(self):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001225 return len(self._options())
Łukasz Langa26d513c2010-11-10 18:57:39 +00001226
1227 def __iter__(self):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001228 return self._options().__iter__()
1229
1230 def _options(self):
1231 if self._name != self._parser.default_section:
1232 return self._parser.options(self._name)
1233 else:
1234 return self._parser.defaults()
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001235
Łukasz Langa2f0fd0f2010-12-04 17:48:18 +00001236 def get(self, option, fallback=None, *, raw=False, vars=None):
1237 return self._parser.get(self._name, option, raw=raw, vars=vars,
1238 fallback=fallback)
1239
1240 def getint(self, option, fallback=None, *, raw=False, vars=None):
1241 return self._parser.getint(self._name, option, raw=raw, vars=vars,
1242 fallback=fallback)
1243
1244 def getfloat(self, option, fallback=None, *, raw=False, vars=None):
1245 return self._parser.getfloat(self._name, option, raw=raw, vars=vars,
1246 fallback=fallback)
1247
1248 def getboolean(self, option, fallback=None, *, raw=False, vars=None):
1249 return self._parser.getboolean(self._name, option, raw=raw, vars=vars,
1250 fallback=fallback)
1251
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001252 @property
1253 def parser(self):
1254 # The parser object of the proxy is read-only.
1255 return self._parser
1256
1257 @property
1258 def name(self):
1259 # The name of the section on a proxy is read-only.
1260 return self._name