blob: eac508e41245b64bd6cf38ddce5fce0e0cd3ffa3 [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 Rossum360e4b82007-05-14 22:51:27 +0000147 def _get_message(self):
148 """Getter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000149 BaseException.
150 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000151 return self.__message
152
153 def _set_message(self, value):
154 """Setter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000155 BaseException.
156 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000157 self.__message = value
158
159 # BaseException.message has been deprecated since Python 2.6. To prevent
Fred Drakea4923622010-08-09 12:52:45 +0000160 # DeprecationWarning from popping up over this pre-existing attribute, use
161 # a new property that takes lookup precedence.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000162 message = property(_get_message, _set_message)
163
Guido van Rossum3d209861997-12-09 16:10:31 +0000164 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000165 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000166 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000167
Guido van Rossum3d209861997-12-09 16:10:31 +0000168 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000169 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000170
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000171 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000172
Georg Brandl96a60ae2010-07-28 13:13:46 +0000173
Guido van Rossum3d209861997-12-09 16:10:31 +0000174class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000175 """Raised when no section matches a requested option."""
176
Guido van Rossum3d209861997-12-09 16:10:31 +0000177 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000178 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000179 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000180 self.args = (section, )
Guido van Rossum3d209861997-12-09 16:10:31 +0000181
Georg Brandl96a60ae2010-07-28 13:13:46 +0000182
Guido van Rossum3d209861997-12-09 16:10:31 +0000183class DuplicateSectionError(Error):
Fred Drakea4923622010-08-09 12:52:45 +0000184 """Raised when a section is repeated in an input source.
Fred Drake8d5dd982002-12-30 23:51:45 +0000185
Fred Drakea4923622010-08-09 12:52:45 +0000186 Possible repetitions that raise this exception are: multiple creation
187 using the API or in strict parsers when a section is found more than once
188 in a single input file, string or dictionary.
189 """
190
191 def __init__(self, section, source=None, lineno=None):
192 msg = [repr(section), " already exists"]
193 if source is not None:
194 message = ["While reading from ", source]
195 if lineno is not None:
196 message.append(" [line {0:2d}]".format(lineno))
197 message.append(": section ")
198 message.extend(msg)
199 msg = message
200 else:
201 msg.insert(0, "Section ")
202 Error.__init__(self, "".join(msg))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000203 self.section = section
Fred Drakea4923622010-08-09 12:52:45 +0000204 self.source = source
205 self.lineno = lineno
206 self.args = (section, source, lineno)
207
208
209class DuplicateOptionError(Error):
210 """Raised by strict parsers when an option is repeated in an input source.
211
212 Current implementation raises this exception only when an option is found
213 more than once in a single file, string or dictionary.
214 """
215
216 def __init__(self, section, option, source=None, lineno=None):
217 msg = [repr(option), " in section ", repr(section),
218 " already exists"]
219 if source is not None:
220 message = ["While reading from ", source]
221 if lineno is not None:
222 message.append(" [line {0:2d}]".format(lineno))
223 message.append(": option ")
224 message.extend(msg)
225 msg = message
226 else:
227 msg.insert(0, "Option ")
228 Error.__init__(self, "".join(msg))
229 self.section = section
230 self.option = option
231 self.source = source
232 self.lineno = lineno
233 self.args = (section, option, source, lineno)
Guido van Rossum3d209861997-12-09 16:10:31 +0000234
Georg Brandl96a60ae2010-07-28 13:13:46 +0000235
Guido van Rossum3d209861997-12-09 16:10:31 +0000236class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000237 """A requested option was not found."""
238
Guido van Rossum3d209861997-12-09 16:10:31 +0000239 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000240 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000241 (option, section))
242 self.option = option
243 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000244 self.args = (option, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000245
Georg Brandl96a60ae2010-07-28 13:13:46 +0000246
Guido van Rossum3d209861997-12-09 16:10:31 +0000247class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000248 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000249
Fred Drakee2c64912002-12-31 17:23:27 +0000250 def __init__(self, option, section, msg):
251 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000252 self.option = option
253 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000254 self.args = (option, section, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000255
Georg Brandl96a60ae2010-07-28 13:13:46 +0000256
Fred Drakee2c64912002-12-31 17:23:27 +0000257class InterpolationMissingOptionError(InterpolationError):
258 """A string substitution required a setting which was not available."""
259
260 def __init__(self, option, section, rawval, reference):
261 msg = ("Bad value substitution:\n"
262 "\tsection: [%s]\n"
263 "\toption : %s\n"
264 "\tkey : %s\n"
265 "\trawval : %s\n"
266 % (section, option, reference, rawval))
267 InterpolationError.__init__(self, option, section, msg)
268 self.reference = reference
Michael Foordbd6c0792010-07-25 23:09:25 +0000269 self.args = (option, section, rawval, reference)
Fred Drakee2c64912002-12-31 17:23:27 +0000270
Georg Brandl96a60ae2010-07-28 13:13:46 +0000271
Fred Drakee2c64912002-12-31 17:23:27 +0000272class InterpolationSyntaxError(InterpolationError):
Fred Drakea4923622010-08-09 12:52:45 +0000273 """Raised when the source text contains invalid syntax.
274
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000275 Current implementation raises this exception when the source text into
276 which substitutions are made does not conform to the required syntax.
Fred Drakea4923622010-08-09 12:52:45 +0000277 """
Neal Norwitzce1d9442002-12-30 23:38:47 +0000278
Georg Brandl96a60ae2010-07-28 13:13:46 +0000279
Fred Drakee2c64912002-12-31 17:23:27 +0000280class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000281 """Raised when substitutions are nested too deeply."""
282
Fred Drake2a37f9f2000-09-27 22:43:54 +0000283 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000284 msg = ("Value interpolation too deeply recursive:\n"
285 "\tsection: [%s]\n"
286 "\toption : %s\n"
287 "\trawval : %s\n"
288 % (section, option, rawval))
289 InterpolationError.__init__(self, option, section, msg)
Michael Foordbd6c0792010-07-25 23:09:25 +0000290 self.args = (option, section, rawval)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000291
Georg Brandl96a60ae2010-07-28 13:13:46 +0000292
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000293class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000294 """Raised when a configuration file does not follow legal syntax."""
295
Fred Drakea4923622010-08-09 12:52:45 +0000296 def __init__(self, source=None, filename=None):
297 # Exactly one of `source'/`filename' arguments has to be given.
298 # `filename' kept for compatibility.
299 if filename and source:
300 raise ValueError("Cannot specify both `filename' and `source'. "
301 "Use `source'.")
302 elif not filename and not source:
303 raise ValueError("Required argument `source' not given.")
304 elif filename:
305 source = filename
306 Error.__init__(self, 'Source contains parsing errors: %s' % source)
307 self.source = source
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000308 self.errors = []
Fred Drakea4923622010-08-09 12:52:45 +0000309 self.args = (source, )
310
311 @property
312 def filename(self):
313 """Deprecated, use `source'."""
314 warnings.warn(
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000315 "The 'filename' attribute will be removed in future versions. "
Fred Drakea4923622010-08-09 12:52:45 +0000316 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000317 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000318 )
319 return self.source
320
321 @filename.setter
322 def filename(self, value):
323 """Deprecated, user `source'."""
324 warnings.warn(
325 "The 'filename' attribute will be removed in future versions. "
326 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000327 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000328 )
329 self.source = value
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000330
331 def append(self, lineno, line):
332 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000333 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000334
Georg Brandl96a60ae2010-07-28 13:13:46 +0000335
Fred Drake2a37f9f2000-09-27 22:43:54 +0000336class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000337 """Raised when a key-value pair is found before any section header."""
338
Fred Drake2a37f9f2000-09-27 22:43:54 +0000339 def __init__(self, filename, lineno, line):
340 Error.__init__(
341 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000342 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000343 (filename, lineno, line))
Fred Drakea4923622010-08-09 12:52:45 +0000344 self.source = filename
Fred Drake2a37f9f2000-09-27 22:43:54 +0000345 self.lineno = lineno
346 self.line = line
Michael Foordbd6c0792010-07-25 23:09:25 +0000347 self.args = (filename, lineno, line)
Guido van Rossum3d209861997-12-09 16:10:31 +0000348
Georg Brandl96a60ae2010-07-28 13:13:46 +0000349
Fred Drakecc645b92010-09-04 04:35:34 +0000350# Used in parser getters to indicate the default behaviour when a specific
351# option is not found it to raise an exception. Created to enable `None' as
352# a valid fallback value.
353_UNSET = object()
354
355
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000356class Interpolation:
357 """Dummy interpolation that passes the value through with no changes."""
358
359 def before_get(self, parser, section, option, value, defaults):
360 return value
361
362 def before_set(self, parser, section, option, value):
363 return value
364
365 def before_read(self, parser, section, option, value):
366 return value
367
368 def before_write(self, parser, section, option, value):
369 return value
370
371
372class BasicInterpolation(Interpolation):
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000373 """Interpolation as implemented in the classic ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000374
375 The option values can contain format strings which refer to other values in
376 the same section, or values in the special default section.
377
378 For example:
379
380 something: %(dir)s/whatever
381
382 would resolve the "%(dir)s" to the value of dir. All reference
383 expansions are done late, on demand. If a user needs to use a bare % in
Ezio Melottie130a522011-10-19 10:58:56 +0300384 a configuration file, she can escape it by writing %%. Other % usage
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000385 is considered a user error and raises `InterpolationSyntaxError'."""
386
387 _KEYCRE = re.compile(r"%\(([^)]+)\)s")
388
389 def before_get(self, parser, section, option, value, defaults):
390 L = []
391 self._interpolate_some(parser, option, L, value, section, defaults, 1)
392 return ''.join(L)
393
394 def before_set(self, parser, section, option, value):
395 tmp_value = value.replace('%%', '') # escaped percent signs
396 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
397 if '%' in tmp_value:
398 raise ValueError("invalid interpolation syntax in %r at "
399 "position %d" % (value, tmp_value.find('%')))
400 return value
401
402 def _interpolate_some(self, parser, option, accum, rest, section, map,
403 depth):
404 if depth > MAX_INTERPOLATION_DEPTH:
405 raise InterpolationDepthError(option, section, rest)
406 while rest:
407 p = rest.find("%")
408 if p < 0:
409 accum.append(rest)
410 return
411 if p > 0:
412 accum.append(rest[:p])
413 rest = rest[p:]
414 # p is no longer used
415 c = rest[1:2]
416 if c == "%":
417 accum.append("%")
418 rest = rest[2:]
419 elif c == "(":
420 m = self._KEYCRE.match(rest)
421 if m is None:
422 raise InterpolationSyntaxError(option, section,
423 "bad interpolation variable reference %r" % rest)
424 var = parser.optionxform(m.group(1))
425 rest = rest[m.end():]
426 try:
427 v = map[var]
428 except KeyError:
429 raise InterpolationMissingOptionError(
430 option, section, rest, var)
431 if "%" in v:
432 self._interpolate_some(parser, option, accum, v,
433 section, map, depth + 1)
434 else:
435 accum.append(v)
436 else:
437 raise InterpolationSyntaxError(
438 option, section,
439 "'%%' must be followed by '%%' or '(', "
440 "found: %r" % (rest,))
441
442
443class ExtendedInterpolation(Interpolation):
444 """Advanced variant of interpolation, supports the syntax used by
445 `zc.buildout'. Enables interpolation between sections."""
446
447 _KEYCRE = re.compile(r"\$\{([^}]+)\}")
448
449 def before_get(self, parser, section, option, value, defaults):
450 L = []
451 self._interpolate_some(parser, option, L, value, section, defaults, 1)
452 return ''.join(L)
453
454 def before_set(self, parser, section, option, value):
455 tmp_value = value.replace('$$', '') # escaped dollar signs
456 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
457 if '$' in tmp_value:
458 raise ValueError("invalid interpolation syntax in %r at "
459 "position %d" % (value, tmp_value.find('%')))
460 return value
461
462 def _interpolate_some(self, parser, option, accum, rest, section, map,
463 depth):
464 if depth > MAX_INTERPOLATION_DEPTH:
465 raise InterpolationDepthError(option, section, rest)
466 while rest:
467 p = rest.find("$")
468 if p < 0:
469 accum.append(rest)
470 return
471 if p > 0:
472 accum.append(rest[:p])
473 rest = rest[p:]
474 # p is no longer used
475 c = rest[1:2]
476 if c == "$":
477 accum.append("$")
478 rest = rest[2:]
479 elif c == "{":
480 m = self._KEYCRE.match(rest)
481 if m is None:
482 raise InterpolationSyntaxError(option, section,
483 "bad interpolation variable reference %r" % rest)
Łukasz Langae698cd52011-04-28 10:58:57 +0200484 path = m.group(1).split(':')
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000485 rest = rest[m.end():]
486 sect = section
487 opt = option
488 try:
489 if len(path) == 1:
Łukasz Langae698cd52011-04-28 10:58:57 +0200490 opt = parser.optionxform(path[0])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000491 v = map[opt]
492 elif len(path) == 2:
493 sect = path[0]
Łukasz Langae698cd52011-04-28 10:58:57 +0200494 opt = parser.optionxform(path[1])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000495 v = parser.get(sect, opt, raw=True)
496 else:
497 raise InterpolationSyntaxError(
498 option, section,
499 "More than one ':' found: %r" % (rest,))
Łukasz Langa71b37a52010-12-17 21:56:32 +0000500 except (KeyError, NoSectionError, NoOptionError):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000501 raise InterpolationMissingOptionError(
Łukasz Langa71b37a52010-12-17 21:56:32 +0000502 option, section, rest, ":".join(path))
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000503 if "$" in v:
504 self._interpolate_some(parser, opt, accum, v, sect,
505 dict(parser.items(sect, raw=True)),
506 depth + 1)
507 else:
508 accum.append(v)
509 else:
510 raise InterpolationSyntaxError(
511 option, section,
512 "'$' must be followed by '$' or '{', "
513 "found: %r" % (rest,))
514
515
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000516class LegacyInterpolation(Interpolation):
517 """Deprecated interpolation used in old versions of ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000518 Use BasicInterpolation or ExtendedInterpolation instead."""
519
520 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
521
522 def before_get(self, parser, section, option, value, vars):
523 rawval = value
524 depth = MAX_INTERPOLATION_DEPTH
525 while depth: # Loop through this until it's done
526 depth -= 1
527 if value and "%(" in value:
528 replace = functools.partial(self._interpolation_replace,
529 parser=parser)
530 value = self._KEYCRE.sub(replace, value)
531 try:
532 value = value % vars
533 except KeyError as e:
534 raise InterpolationMissingOptionError(
535 option, section, rawval, e.args[0])
536 else:
537 break
538 if value and "%(" in value:
539 raise InterpolationDepthError(option, section, rawval)
540 return value
541
542 def before_set(self, parser, section, option, value):
543 return value
544
545 @staticmethod
546 def _interpolation_replace(match, parser):
547 s = match.group(1)
548 if s is None:
549 return match.group()
550 else:
551 return "%%(%s)s" % parser.optionxform(s)
552
553
Łukasz Langa26d513c2010-11-10 18:57:39 +0000554class RawConfigParser(MutableMapping):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000555 """ConfigParser that does not do interpolation."""
556
557 # Regular expressions for parsing section headers and options
558 _SECT_TMPL = r"""
559 \[ # [
560 (?P<header>[^]]+) # very permissive!
561 \] # ]
562 """
563 _OPT_TMPL = r"""
564 (?P<option>.*?) # very permissive!
565 \s*(?P<vi>{delim})\s* # any number of space/tab,
566 # followed by any of the
567 # allowed delimiters,
568 # followed by any space/tab
569 (?P<value>.*)$ # everything up to eol
570 """
571 _OPT_NV_TMPL = r"""
572 (?P<option>.*?) # very permissive!
573 \s*(?: # any number of space/tab,
574 (?P<vi>{delim})\s* # optionally followed by
575 # any of the allowed
576 # delimiters, followed by any
577 # space/tab
578 (?P<value>.*))?$ # everything up to eol
579 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000580 # Interpolation algorithm to be used if the user does not specify another
581 _DEFAULT_INTERPOLATION = Interpolation()
Georg Brandl96a60ae2010-07-28 13:13:46 +0000582 # Compiled regular expression for matching sections
583 SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
584 # Compiled regular expression for matching options with typical separators
585 OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
586 # Compiled regular expression for matching options with optional values
587 # delimited using typical separators
588 OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
589 # Compiled regular expression for matching leading whitespace in a line
590 NONSPACECRE = re.compile(r"\S")
Fred Drakecc645b92010-09-04 04:35:34 +0000591 # Possible boolean values in the configuration.
592 BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
593 '0': False, 'no': False, 'false': False, 'off': False}
Georg Brandl96a60ae2010-07-28 13:13:46 +0000594
Fred Drake03c44a32010-02-19 06:08:41 +0000595 def __init__(self, defaults=None, dict_type=_default_dict,
Fred Drakea4923622010-08-09 12:52:45 +0000596 allow_no_value=False, *, delimiters=('=', ':'),
Łukasz Langab25a7912010-12-17 01:32:29 +0000597 comment_prefixes=('#', ';'), inline_comment_prefixes=None,
598 strict=True, empty_lines_in_values=True,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000599 default_section=DEFAULTSECT,
600 interpolation=_UNSET):
601
Thomas Wouters89f507f2006-12-13 04:49:30 +0000602 self._dict = dict_type
603 self._sections = self._dict()
604 self._defaults = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000605 self._proxies = self._dict()
Łukasz Langac264c092010-11-20 16:15:37 +0000606 self._proxies[default_section] = SectionProxy(self, default_section)
David Goodger68a1abd2004-10-03 15:40:25 +0000607 if defaults:
608 for key, value in defaults.items():
609 self._defaults[self.optionxform(key)] = value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000610 self._delimiters = tuple(delimiters)
611 if delimiters == ('=', ':'):
612 self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
613 else:
Fred Drakea4923622010-08-09 12:52:45 +0000614 d = "|".join(re.escape(d) for d in delimiters)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000615 if allow_no_value:
Fred Drakea4923622010-08-09 12:52:45 +0000616 self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000617 re.VERBOSE)
618 else:
Fred Drakea4923622010-08-09 12:52:45 +0000619 self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000620 re.VERBOSE)
Łukasz Langab25a7912010-12-17 01:32:29 +0000621 self._comment_prefixes = tuple(comment_prefixes or ())
622 self._inline_comment_prefixes = tuple(inline_comment_prefixes or ())
Fred Drakea4923622010-08-09 12:52:45 +0000623 self._strict = strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000624 self._allow_no_value = allow_no_value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000625 self._empty_lines_in_values = empty_lines_in_values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000626 self.default_section=default_section
Łukasz Langa1aa422f2011-04-28 17:03:45 +0200627 self._interpolation = interpolation
628 if self._interpolation is _UNSET:
629 self._interpolation = self._DEFAULT_INTERPOLATION
630 if self._interpolation is None:
631 self._interpolation = Interpolation()
Guido van Rossum3d209861997-12-09 16:10:31 +0000632
633 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000634 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000635
636 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000637 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000638 # self._sections will never have [DEFAULT] in it
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000639 return list(self._sections.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000640
641 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000642 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000643
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000644 Raise DuplicateSectionError if a section by the specified name
Łukasz Langac264c092010-11-20 16:15:37 +0000645 already exists. Raise ValueError if name is DEFAULT.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000646 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000647 if section == self.default_section:
Łukasz Langa3a11e712010-12-03 22:15:19 +0000648 raise ValueError('Invalid section name: %r' % section)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000649
Fred Drakefce65572002-10-25 18:08:18 +0000650 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000651 raise DuplicateSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000652 self._sections[section] = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000653 self._proxies[section] = SectionProxy(self, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000654
655 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000656 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000657
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000658 The DEFAULT section is not acknowledged.
659 """
Fred Drakefce65572002-10-25 18:08:18 +0000660 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000661
662 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000663 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000664 try:
Fred Drakefce65572002-10-25 18:08:18 +0000665 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000666 except KeyError:
667 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000668 opts.update(self._defaults)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000669 return list(opts.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000670
Georg Brandl8dcaa732010-07-29 12:17:40 +0000671 def read(self, filenames, encoding=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000672 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000673
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000674 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000675 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000676 configuration file locations (e.g. current directory, user's
677 home directory, systemwide directory), and all existing
678 configuration files in the list will be read. A single
679 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000680
681 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000682 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000683 if isinstance(filenames, str):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000684 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000685 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000686 for filename in filenames:
687 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000688 with open(filename, encoding=encoding) as fp:
689 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000690 except IOError:
691 continue
Fred Drake82903142004-05-18 04:24:02 +0000692 read_ok.append(filename)
693 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000694
Fred Drakea4923622010-08-09 12:52:45 +0000695 def read_file(self, f, source=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000696 """Like read() but the argument must be a file-like object.
697
Łukasz Langadaab1c82011-04-27 18:10:05 +0200698 The `f' argument must be iterable, returning one line at a time.
699 Optional second argument is the `source' specifying the name of the
700 file being read. If not given, it is taken from f.name. If `f' has no
701 `name' attribute, `<???>' is used.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000702 """
Fred Drakea4923622010-08-09 12:52:45 +0000703 if source is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000704 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000705 source = f.name
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000706 except AttributeError:
Fred Drakea4923622010-08-09 12:52:45 +0000707 source = '<???>'
708 self._read(f, source)
709
710 def read_string(self, string, source='<string>'):
711 """Read configuration from a given string."""
712 sfile = io.StringIO(string)
713 self.read_file(sfile, source)
714
715 def read_dict(self, dictionary, source='<dict>'):
716 """Read configuration from a dictionary.
717
718 Keys are section names, values are dictionaries with keys and values
719 that should be present in the section. If the used dictionary type
720 preserves order, sections and their keys will be added in order.
721
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000722 All types held in the dictionary are converted to strings during
723 reading, including section names, option names and keys.
724
Fred Drakea4923622010-08-09 12:52:45 +0000725 Optional second argument is the `source' specifying the name of the
726 dictionary being read.
727 """
728 elements_added = set()
729 for section, keys in dictionary.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000730 section = str(section)
Fred Drakea4923622010-08-09 12:52:45 +0000731 try:
732 self.add_section(section)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000733 except (DuplicateSectionError, ValueError):
Fred Drakea4923622010-08-09 12:52:45 +0000734 if self._strict and section in elements_added:
735 raise
Łukasz Langa71b37a52010-12-17 21:56:32 +0000736 elements_added.add(section)
Fred Drakea4923622010-08-09 12:52:45 +0000737 for key, value in keys.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000738 key = self.optionxform(str(key))
Fred Drakecc645b92010-09-04 04:35:34 +0000739 if value is not None:
740 value = str(value)
Fred Drakea4923622010-08-09 12:52:45 +0000741 if self._strict and (section, key) in elements_added:
742 raise DuplicateOptionError(section, key, source)
743 elements_added.add((section, key))
744 self.set(section, key, value)
745
746 def readfp(self, fp, filename=None):
747 """Deprecated, use read_file instead."""
748 warnings.warn(
749 "This method will be removed in future versions. "
750 "Use 'parser.read_file()' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000751 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000752 )
753 self.read_file(fp, source=filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000754
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000755 def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000756 """Get an option value for a given section.
757
758 If `vars' is provided, it must be a dictionary. The option is looked up
759 in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000760 If the key is not found and `fallback' is provided, it is used as
761 a fallback value. `None' can be provided as a `fallback' value.
762
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000763 If interpolation is enabled and the optional argument `raw' is False,
764 all interpolations are expanded in the return values.
765
766 Arguments `raw', `vars', and `fallback' are keyword only.
767
768 The section DEFAULT is special.
Fred Drakecc645b92010-09-04 04:35:34 +0000769 """
770 try:
771 d = self._unify_values(section, vars)
772 except NoSectionError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000773 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000774 raise
Fred Drakefce65572002-10-25 18:08:18 +0000775 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000776 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000777 option = self.optionxform(option)
778 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000779 value = d[option]
Fred Drakecc645b92010-09-04 04:35:34 +0000780 except KeyError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000781 if fallback is _UNSET:
Fred Drakefce65572002-10-25 18:08:18 +0000782 raise NoOptionError(option, section)
Fred Drakecc645b92010-09-04 04:35:34 +0000783 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000784 return fallback
Fred Drake2a37f9f2000-09-27 22:43:54 +0000785
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000786 if raw or value is None:
787 return value
788 else:
789 return self._interpolation.before_get(self, section, option, value,
790 d)
Fred Drake2ca041f2002-09-27 15:49:56 +0000791
Łukasz Langa26d513c2010-11-10 18:57:39 +0000792 def _get(self, section, conv, option, **kwargs):
793 return conv(self.get(section, option, **kwargs))
Guido van Rossum3d209861997-12-09 16:10:31 +0000794
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000795 def getint(self, section, option, *, raw=False, vars=None,
796 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000797 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000798 return self._get(section, int, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000799 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000800 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000801 raise
802 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000803 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000804
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000805 def getfloat(self, section, option, *, raw=False, vars=None,
806 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000807 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000808 return self._get(section, float, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000809 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000810 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000811 raise
812 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000813 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000814
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000815 def getboolean(self, section, option, *, raw=False, vars=None,
816 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000817 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000818 return self._get(section, self._convert_to_boolean, option,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000819 raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000820 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000821 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000822 raise
823 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000824 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000825
Łukasz Langa71b37a52010-12-17 21:56:32 +0000826 def items(self, section=_UNSET, raw=False, vars=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000827 """Return a list of (name, value) tuples for each option in a section.
828
829 All % interpolations are expanded in the return values, based on the
830 defaults passed into the constructor, unless the optional argument
831 `raw' is true. Additional substitutions may be provided using the
832 `vars' argument, which must be a dictionary whose contents overrides
833 any pre-existing defaults.
834
835 The section DEFAULT is special.
836 """
Łukasz Langa71b37a52010-12-17 21:56:32 +0000837 if section is _UNSET:
838 return super().items()
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000839 d = self._defaults.copy()
840 try:
841 d.update(self._sections[section])
842 except KeyError:
843 if section != self.default_section:
844 raise NoSectionError(section)
845 # Update with the entry specific variables
846 if vars:
847 for key, value in vars.items():
848 d[self.optionxform(key)] = value
Łukasz Langa24bcc612010-12-04 11:48:11 +0000849 value_getter = lambda option: self._interpolation.before_get(self,
850 section, option, d[option], d)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000851 if raw:
Łukasz Langa24bcc612010-12-04 11:48:11 +0000852 value_getter = lambda option: d[option]
853 return [(option, value_getter(option)) for option in d.keys()]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000854
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100855 def popitem(self):
856 """Remove a section from the parser and return it as
857 a (section_name, section_proxy) tuple. If no section is present, raise
858 KeyError.
859
860 The section DEFAULT is never returned because it cannot be removed.
861 """
862 for key in self.sections():
863 value = self[key]
864 del self[key]
865 return key, value
866 raise KeyError
867
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000868 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000869 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000870
Eric S. Raymond417c4892000-07-10 18:11:00 +0000871 def has_option(self, section, option):
Łukasz Langa71b37a52010-12-17 21:56:32 +0000872 """Check for the existence of a given option in a given section.
873 If the specified `section' is None or an empty string, DEFAULT is
874 assumed. If the specified `section' does not exist, returns False."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000875 if not section or section == self.default_section:
Fred Drakec2ff9052002-09-27 15:33:11 +0000876 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000877 return option in self._defaults
878 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000879 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000880 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000881 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000882 return (option in self._sections[section]
883 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000884
Fred Drake03c44a32010-02-19 06:08:41 +0000885 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000886 """Set an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000887 if value:
888 value = self._interpolation.before_set(self, section, option,
889 value)
890 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000891 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000892 else:
893 try:
Fred Drakefce65572002-10-25 18:08:18 +0000894 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000895 except KeyError:
896 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000897 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000898
Georg Brandl96a60ae2010-07-28 13:13:46 +0000899 def write(self, fp, space_around_delimiters=True):
900 """Write an .ini-format representation of the configuration state.
901
902 If `space_around_delimiters' is True (the default), delimiters
903 between keys and values are surrounded by spaces.
904 """
905 if space_around_delimiters:
906 d = " {} ".format(self._delimiters[0])
907 else:
908 d = self._delimiters[0]
Fred Drakefce65572002-10-25 18:08:18 +0000909 if self._defaults:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000910 self._write_section(fp, self.default_section,
Łukasz Langac264c092010-11-20 16:15:37 +0000911 self._defaults.items(), d)
Fred Drakefce65572002-10-25 18:08:18 +0000912 for section in self._sections:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000913 self._write_section(fp, section,
914 self._sections[section].items(), d)
915
916 def _write_section(self, fp, section_name, section_items, delimiter):
917 """Write a single section to the specified `fp'."""
918 fp.write("[{}]\n".format(section_name))
919 for key, value in section_items:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000920 value = self._interpolation.before_write(self, section_name, key,
921 value)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000922 if value is not None or not self._allow_no_value:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000923 value = delimiter + str(value).replace('\n', '\n\t')
924 else:
925 value = ""
926 fp.write("{}{}\n".format(key, value))
927 fp.write("\n")
Eric S. Raymond417c4892000-07-10 18:11:00 +0000928
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000929 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000930 """Remove an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000931 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000932 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000933 else:
934 try:
Fred Drakefce65572002-10-25 18:08:18 +0000935 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000936 except KeyError:
937 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000938 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000939 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000940 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000941 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000942 return existed
943
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000944 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000945 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000946 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000947 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000948 del self._sections[section]
Łukasz Langa49afa382010-11-11 19:53:23 +0000949 del self._proxies[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000950 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000951
Łukasz Langa26d513c2010-11-10 18:57:39 +0000952 def __getitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000953 if key != self.default_section and not self.has_section(key):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000954 raise KeyError(key)
Łukasz Langa49afa382010-11-11 19:53:23 +0000955 return self._proxies[key]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000956
957 def __setitem__(self, key, value):
958 # To conform with the mapping protocol, overwrites existing values in
959 # the section.
960
961 # XXX this is not atomic if read_dict fails at any point. Then again,
962 # no update method in configparser is atomic in this implementation.
Łukasz Langa02101942012-12-31 13:55:11 +0100963 if key == self.default_section:
964 self._defaults.clear()
965 else:
966 self.remove_section(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000967 self.read_dict({key: value})
968
969 def __delitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000970 if key == self.default_section:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000971 raise ValueError("Cannot remove the default section.")
972 if not self.has_section(key):
973 raise KeyError(key)
974 self.remove_section(key)
975
976 def __contains__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000977 return key == self.default_section or self.has_section(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000978
979 def __len__(self):
980 return len(self._sections) + 1 # the default section
981
982 def __iter__(self):
983 # XXX does it break when underlying container state changed?
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000984 return itertools.chain((self.default_section,), self._sections.keys())
Łukasz Langa26d513c2010-11-10 18:57:39 +0000985
Fred Drakefce65572002-10-25 18:08:18 +0000986 def _read(self, fp, fpname):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000987 """Parse a sectioned configuration file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000988
Fred Drakea4923622010-08-09 12:52:45 +0000989 Each section in a configuration file contains a header, indicated by
990 a name in square brackets (`[]'), plus key/value options, indicated by
Georg Brandl96a60ae2010-07-28 13:13:46 +0000991 `name' and `value' delimited with a specific substring (`=' or `:' by
992 default).
993
Fred Drakea4923622010-08-09 12:52:45 +0000994 Values can span multiple lines, as long as they are indented deeper
995 than the first line of the value. Depending on the parser's mode, blank
996 lines may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000997
998 Configuration files may include comments, prefixed by specific
Fred Drakea4923622010-08-09 12:52:45 +0000999 characters (`#' and `;' by default). Comments may appear on their own
1000 in an otherwise empty line or may be entered in lines holding values or
Georg Brandl96a60ae2010-07-28 13:13:46 +00001001 section names.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001002 """
Fred Drakea4923622010-08-09 12:52:45 +00001003 elements_added = set()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001004 cursect = None # None, or a dictionary
Fred Drakea4923622010-08-09 12:52:45 +00001005 sectname = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001006 optname = None
1007 lineno = 0
Georg Brandl96a60ae2010-07-28 13:13:46 +00001008 indent_level = 0
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001009 e = None # None, or an exception
Georg Brandl96a60ae2010-07-28 13:13:46 +00001010 for lineno, line in enumerate(fp, start=1):
Łukasz Langacba24322012-07-07 18:54:08 +02001011 comment_start = sys.maxsize
Georg Brandl96a60ae2010-07-28 13:13:46 +00001012 # strip inline comments
Łukasz Langacba24322012-07-07 18:54:08 +02001013 inline_prefixes = {p: -1 for p in self._inline_comment_prefixes}
1014 while comment_start == sys.maxsize and inline_prefixes:
1015 next_prefixes = {}
1016 for prefix, index in inline_prefixes.items():
1017 index = line.find(prefix, index+1)
1018 if index == -1:
1019 continue
1020 next_prefixes[prefix] = index
1021 if index == 0 or (index > 0 and line[index-1].isspace()):
1022 comment_start = min(comment_start, index)
1023 inline_prefixes = next_prefixes
Łukasz Langab25a7912010-12-17 01:32:29 +00001024 # strip full line comments
1025 for prefix in self._comment_prefixes:
1026 if line.strip().startswith(prefix):
1027 comment_start = 0
1028 break
Łukasz Langacba24322012-07-07 18:54:08 +02001029 if comment_start == sys.maxsize:
1030 comment_start = None
Georg Brandl96a60ae2010-07-28 13:13:46 +00001031 value = line[:comment_start].strip()
1032 if not value:
Georg Brandlf206d0e2010-07-29 11:56:20 +00001033 if self._empty_lines_in_values:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001034 # add empty line to the value, but only if there was no
1035 # comment on the line
Georg Brandlf206d0e2010-07-29 11:56:20 +00001036 if (comment_start is None and
1037 cursect is not None and
1038 optname and
1039 cursect[optname] is not None):
1040 cursect[optname].append('') # newlines added at join
Georg Brandl96a60ae2010-07-28 13:13:46 +00001041 else:
1042 # empty line marks end of value
1043 indent_level = sys.maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001044 continue
1045 # continuation line?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001046 first_nonspace = self.NONSPACECRE.search(line)
1047 cur_indent_level = first_nonspace.start() if first_nonspace else 0
1048 if (cursect is not None and optname and
1049 cur_indent_level > indent_level):
1050 cursect[optname].append(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001051 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001052 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001053 indent_level = cur_indent_level
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001054 # is it a section header?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001055 mo = self.SECTCRE.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001056 if mo:
1057 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +00001058 if sectname in self._sections:
Fred Drakea4923622010-08-09 12:52:45 +00001059 if self._strict and sectname in elements_added:
1060 raise DuplicateSectionError(sectname, fpname,
1061 lineno)
Fred Drakefce65572002-10-25 18:08:18 +00001062 cursect = self._sections[sectname]
Fred Drakea4923622010-08-09 12:52:45 +00001063 elements_added.add(sectname)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001064 elif sectname == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001065 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001066 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001067 cursect = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +00001068 self._sections[sectname] = cursect
Łukasz Langa49afa382010-11-11 19:53:23 +00001069 self._proxies[sectname] = SectionProxy(self, sectname)
Fred Drakea4923622010-08-09 12:52:45 +00001070 elements_added.add(sectname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001071 # So sections can't start with a continuation line
1072 optname = None
1073 # no section header in the file?
1074 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001075 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001076 # an option line?
1077 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001078 mo = self._optcre.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001079 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +00001080 optname, vi, optval = mo.group('option', 'vi', 'value')
Georg Brandl96a60ae2010-07-28 13:13:46 +00001081 if not optname:
1082 e = self._handle_error(e, fpname, lineno, line)
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001083 optname = self.optionxform(optname.rstrip())
Fred Drakea4923622010-08-09 12:52:45 +00001084 if (self._strict and
1085 (sectname, optname) in elements_added):
1086 raise DuplicateOptionError(sectname, optname,
1087 fpname, lineno)
1088 elements_added.add((sectname, optname))
Fred Drake03c44a32010-02-19 06:08:41 +00001089 # This check is fine because the OPTCRE cannot
1090 # match if it would set optval to None
1091 if optval is not None:
Fred Drake03c44a32010-02-19 06:08:41 +00001092 optval = optval.strip()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001093 cursect[optname] = [optval]
1094 else:
1095 # valueless option handling
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001096 cursect[optname] = None
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001097 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001098 # a non-fatal parsing error occurred. set up the
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001099 # exception but keep going. the exception will be
1100 # raised at the end of the file and will contain a
1101 # list of all bogus lines
Georg Brandl96a60ae2010-07-28 13:13:46 +00001102 e = self._handle_error(e, fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001103 # if any parsing errors occurred, raise an exception
1104 if e:
1105 raise e
Georg Brandl96a60ae2010-07-28 13:13:46 +00001106 self._join_multiline_values()
Fred Drakefce65572002-10-25 18:08:18 +00001107
Georg Brandl96a60ae2010-07-28 13:13:46 +00001108 def _join_multiline_values(self):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001109 defaults = self.default_section, self._defaults
1110 all_sections = itertools.chain((defaults,),
1111 self._sections.items())
1112 for section, options in all_sections:
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001113 for name, val in options.items():
1114 if isinstance(val, list):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001115 val = '\n'.join(val).rstrip()
1116 options[name] = self._interpolation.before_read(self,
1117 section,
1118 name, val)
Fred Drakefce65572002-10-25 18:08:18 +00001119
Georg Brandl96a60ae2010-07-28 13:13:46 +00001120 def _handle_error(self, exc, fpname, lineno, line):
1121 if not exc:
1122 exc = ParsingError(fpname)
1123 exc.append(lineno, repr(line))
1124 return exc
1125
Fred Drakecc645b92010-09-04 04:35:34 +00001126 def _unify_values(self, section, vars):
Raymond Hettingerddb52402011-02-21 19:42:11 +00001127 """Create a sequence of lookups with 'vars' taking priority over
1128 the 'section' which takes priority over the DEFAULTSECT.
1129
Fred Drakefce65572002-10-25 18:08:18 +00001130 """
Raymond Hettingerddb52402011-02-21 19:42:11 +00001131 sectiondict = {}
Fred Drakefce65572002-10-25 18:08:18 +00001132 try:
Raymond Hettingerddb52402011-02-21 19:42:11 +00001133 sectiondict = self._sections[section]
Fred Drakefce65572002-10-25 18:08:18 +00001134 except KeyError:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001135 if section != self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001136 raise NoSectionError(section)
1137 # Update with the entry specific variables
Raymond Hettingerddb52402011-02-21 19:42:11 +00001138 vardict = {}
David Goodger68a1abd2004-10-03 15:40:25 +00001139 if vars:
1140 for key, value in vars.items():
Fred Drakecc645b92010-09-04 04:35:34 +00001141 if value is not None:
1142 value = str(value)
Raymond Hettingerddb52402011-02-21 19:42:11 +00001143 vardict[self.optionxform(key)] = value
1144 return _ChainMap(vardict, sectiondict, self._defaults)
Fred Drakecc645b92010-09-04 04:35:34 +00001145
1146 def _convert_to_boolean(self, value):
1147 """Return a boolean value translating from other types if necessary.
1148 """
1149 if value.lower() not in self.BOOLEAN_STATES:
1150 raise ValueError('Not a boolean: %s' % value)
1151 return self.BOOLEAN_STATES[value.lower()]
1152
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001153 def _validate_value_types(self, *, section="", option="", value=""):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001154 """Raises a TypeError for non-string values.
1155
1156 The only legal non-string value if we allow valueless
1157 options is None, so we need to check if the value is a
1158 string if:
1159 - we do not allow valueless options, or
1160 - we allow valueless options but the value is not None
1161
1162 For compatibility reasons this method is not used in classic set()
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001163 for RawConfigParsers. It is invoked in every case for mapping protocol
1164 access and in ConfigParser.set().
Łukasz Langa26d513c2010-11-10 18:57:39 +00001165 """
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001166 if not isinstance(section, str):
1167 raise TypeError("section names must be strings")
1168 if not isinstance(option, str):
1169 raise TypeError("option keys must be strings")
Łukasz Langa26d513c2010-11-10 18:57:39 +00001170 if not self._allow_no_value or value:
1171 if not isinstance(value, str):
1172 raise TypeError("option values must be strings")
1173
1174
Fred Drakecc645b92010-09-04 04:35:34 +00001175class ConfigParser(RawConfigParser):
1176 """ConfigParser implementing interpolation."""
1177
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001178 _DEFAULT_INTERPOLATION = BasicInterpolation()
David Goodger1cbf2062004-10-03 15:55:09 +00001179
Fred Drake03c44a32010-02-19 06:08:41 +00001180 def set(self, section, option, value=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001181 """Set an option. Extends RawConfigParser.set by validating type and
1182 interpolation syntax on the value."""
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001183 self._validate_value_types(option=option, value=value)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001184 super().set(section, option, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001185
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001186 def add_section(self, section):
1187 """Create a new section in the configuration. Extends
1188 RawConfigParser.add_section by validating if the section name is
1189 a string."""
1190 self._validate_value_types(section=section)
1191 super().add_section(section)
1192
Łukasz Langa26d513c2010-11-10 18:57:39 +00001193
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001194class SafeConfigParser(ConfigParser):
1195 """ConfigParser alias for backwards compatibility purposes."""
1196
1197 def __init__(self, *args, **kwargs):
1198 super().__init__(*args, **kwargs)
1199 warnings.warn(
1200 "The SafeConfigParser class has been renamed to ConfigParser "
1201 "in Python 3.2. This alias will be removed in future versions."
1202 " Use ConfigParser directly instead.",
1203 DeprecationWarning, stacklevel=2
1204 )
1205
1206
Łukasz Langa26d513c2010-11-10 18:57:39 +00001207class SectionProxy(MutableMapping):
1208 """A proxy for a single section from a parser."""
1209
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001210 def __init__(self, parser, name):
1211 """Creates a view on a section of the specified `name` in `parser`."""
Łukasz Langa26d513c2010-11-10 18:57:39 +00001212 self._parser = parser
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001213 self._name = name
Łukasz Langa26d513c2010-11-10 18:57:39 +00001214
1215 def __repr__(self):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001216 return '<Section: {}>'.format(self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001217
1218 def __getitem__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001219 if not self._parser.has_option(self._name, key):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001220 raise KeyError(key)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001221 return self._parser.get(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001222
1223 def __setitem__(self, key, value):
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001224 self._parser._validate_value_types(option=key, value=value)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001225 return self._parser.set(self._name, key, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001226
1227 def __delitem__(self, key):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001228 if not (self._parser.has_option(self._name, key) and
1229 self._parser.remove_option(self._name, key)):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001230 raise KeyError(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001231
1232 def __contains__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001233 return self._parser.has_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001234
1235 def __len__(self):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001236 return len(self._options())
Łukasz Langa26d513c2010-11-10 18:57:39 +00001237
1238 def __iter__(self):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001239 return self._options().__iter__()
1240
1241 def _options(self):
1242 if self._name != self._parser.default_section:
1243 return self._parser.options(self._name)
1244 else:
1245 return self._parser.defaults()
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001246
Łukasz Langa2f0fd0f2010-12-04 17:48:18 +00001247 def get(self, option, fallback=None, *, raw=False, vars=None):
1248 return self._parser.get(self._name, option, raw=raw, vars=vars,
1249 fallback=fallback)
1250
1251 def getint(self, option, fallback=None, *, raw=False, vars=None):
1252 return self._parser.getint(self._name, option, raw=raw, vars=vars,
1253 fallback=fallback)
1254
1255 def getfloat(self, option, fallback=None, *, raw=False, vars=None):
1256 return self._parser.getfloat(self._name, option, raw=raw, vars=vars,
1257 fallback=fallback)
1258
1259 def getboolean(self, option, fallback=None, *, raw=False, vars=None):
1260 return self._parser.getboolean(self._name, option, raw=raw, vars=vars,
1261 fallback=fallback)
1262
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001263 @property
1264 def parser(self):
1265 # The parser object of the proxy is read-only.
1266 return self._parser
1267
1268 @property
1269 def name(self):
1270 # The name of the section on a proxy is read-only.
1271 return self._name