blob: b843c00cee8852c847e4e25d80cbd3a7ac74621a [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)
102 If section is given, return a list of tuples with (section_name,
103 section_proxy) for each section, including DEFAULTSECT. Otherwise,
104 return a list of tuples with (name, value) for each option
Fred Drake2ca041f2002-09-27 15:49:56 +0000105 in the section.
106
Eric S. Raymond649685a2000-07-14 14:28:22 +0000107 remove_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000108 Remove the given file section and all its options.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000109
110 remove_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000111 Remove the given option from the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000112
113 set(section, option, value)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000114 Set the given option.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000115
Georg Brandl96a60ae2010-07-28 13:13:46 +0000116 write(fp, space_around_delimiters=True)
117 Write the configuration state in .ini format. If
118 `space_around_delimiters' is True (the default), delimiters
119 between keys and values are surrounded by spaces.
Guido van Rossum3d209861997-12-09 16:10:31 +0000120"""
121
Raymond Hettinger57d1a882011-02-23 00:46:28 +0000122from collections.abc import MutableMapping
Raymond Hettinger9fe1ccf2011-02-26 01:02:51 +0000123from collections import OrderedDict as _default_dict, ChainMap as _ChainMap
Łukasz Langa26d513c2010-11-10 18:57:39 +0000124import functools
Fred Drakea4923622010-08-09 12:52:45 +0000125import io
Łukasz Langa26d513c2010-11-10 18:57:39 +0000126import itertools
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000127import re
Georg Brandl96a60ae2010-07-28 13:13:46 +0000128import sys
Fred Drakea4923622010-08-09 12:52:45 +0000129import warnings
Guido van Rossum3d209861997-12-09 16:10:31 +0000130
Fred Drakea4923622010-08-09 12:52:45 +0000131__all__ = ["NoSectionError", "DuplicateOptionError", "DuplicateSectionError",
132 "NoOptionError", "InterpolationError", "InterpolationDepthError",
Fred Drake8d5dd982002-12-30 23:51:45 +0000133 "InterpolationSyntaxError", "ParsingError",
David Goodger1cbf2062004-10-03 15:55:09 +0000134 "MissingSectionHeaderError",
135 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +0000136 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000137
Guido van Rossum3d209861997-12-09 16:10:31 +0000138DEFAULTSECT = "DEFAULT"
139
Fred Drake2a37f9f2000-09-27 22:43:54 +0000140MAX_INTERPOLATION_DEPTH = 10
141
Guido van Rossum3d209861997-12-09 16:10:31 +0000142
Tim Peters88869f92001-01-14 23:36:06 +0000143
Guido van Rossum3d209861997-12-09 16:10:31 +0000144# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000145class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000146 """Base class for ConfigParser exceptions."""
147
Guido van Rossum360e4b82007-05-14 22:51:27 +0000148 def _get_message(self):
149 """Getter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000150 BaseException.
151 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000152 return self.__message
153
154 def _set_message(self, value):
155 """Setter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000156 BaseException.
157 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000158 self.__message = value
159
160 # BaseException.message has been deprecated since Python 2.6. To prevent
Fred Drakea4923622010-08-09 12:52:45 +0000161 # DeprecationWarning from popping up over this pre-existing attribute, use
162 # a new property that takes lookup precedence.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000163 message = property(_get_message, _set_message)
164
Guido van Rossum3d209861997-12-09 16:10:31 +0000165 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000166 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000167 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000168
Guido van Rossum3d209861997-12-09 16:10:31 +0000169 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000170 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000171
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000172 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000173
Georg Brandl96a60ae2010-07-28 13:13:46 +0000174
Guido van Rossum3d209861997-12-09 16:10:31 +0000175class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000176 """Raised when no section matches a requested option."""
177
Guido van Rossum3d209861997-12-09 16:10:31 +0000178 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000179 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000180 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000181 self.args = (section, )
Guido van Rossum3d209861997-12-09 16:10:31 +0000182
Georg Brandl96a60ae2010-07-28 13:13:46 +0000183
Guido van Rossum3d209861997-12-09 16:10:31 +0000184class DuplicateSectionError(Error):
Fred Drakea4923622010-08-09 12:52:45 +0000185 """Raised when a section is repeated in an input source.
Fred Drake8d5dd982002-12-30 23:51:45 +0000186
Fred Drakea4923622010-08-09 12:52:45 +0000187 Possible repetitions that raise this exception are: multiple creation
188 using the API or in strict parsers when a section is found more than once
189 in a single input file, string or dictionary.
190 """
191
192 def __init__(self, section, source=None, lineno=None):
193 msg = [repr(section), " already exists"]
194 if source is not None:
195 message = ["While reading from ", source]
196 if lineno is not None:
197 message.append(" [line {0:2d}]".format(lineno))
198 message.append(": section ")
199 message.extend(msg)
200 msg = message
201 else:
202 msg.insert(0, "Section ")
203 Error.__init__(self, "".join(msg))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000204 self.section = section
Fred Drakea4923622010-08-09 12:52:45 +0000205 self.source = source
206 self.lineno = lineno
207 self.args = (section, source, lineno)
208
209
210class DuplicateOptionError(Error):
211 """Raised by strict parsers when an option is repeated in an input source.
212
213 Current implementation raises this exception only when an option is found
214 more than once in a single file, string or dictionary.
215 """
216
217 def __init__(self, section, option, source=None, lineno=None):
218 msg = [repr(option), " in section ", repr(section),
219 " already exists"]
220 if source is not None:
221 message = ["While reading from ", source]
222 if lineno is not None:
223 message.append(" [line {0:2d}]".format(lineno))
224 message.append(": option ")
225 message.extend(msg)
226 msg = message
227 else:
228 msg.insert(0, "Option ")
229 Error.__init__(self, "".join(msg))
230 self.section = section
231 self.option = option
232 self.source = source
233 self.lineno = lineno
234 self.args = (section, option, source, lineno)
Guido van Rossum3d209861997-12-09 16:10:31 +0000235
Georg Brandl96a60ae2010-07-28 13:13:46 +0000236
Guido van Rossum3d209861997-12-09 16:10:31 +0000237class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000238 """A requested option was not found."""
239
Guido van Rossum3d209861997-12-09 16:10:31 +0000240 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000241 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000242 (option, section))
243 self.option = option
244 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000245 self.args = (option, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000246
Georg Brandl96a60ae2010-07-28 13:13:46 +0000247
Guido van Rossum3d209861997-12-09 16:10:31 +0000248class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000249 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000250
Fred Drakee2c64912002-12-31 17:23:27 +0000251 def __init__(self, option, section, msg):
252 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000253 self.option = option
254 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000255 self.args = (option, section, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000256
Georg Brandl96a60ae2010-07-28 13:13:46 +0000257
Fred Drakee2c64912002-12-31 17:23:27 +0000258class InterpolationMissingOptionError(InterpolationError):
259 """A string substitution required a setting which was not available."""
260
261 def __init__(self, option, section, rawval, reference):
262 msg = ("Bad value substitution:\n"
263 "\tsection: [%s]\n"
264 "\toption : %s\n"
265 "\tkey : %s\n"
266 "\trawval : %s\n"
267 % (section, option, reference, rawval))
268 InterpolationError.__init__(self, option, section, msg)
269 self.reference = reference
Michael Foordbd6c0792010-07-25 23:09:25 +0000270 self.args = (option, section, rawval, reference)
Fred Drakee2c64912002-12-31 17:23:27 +0000271
Georg Brandl96a60ae2010-07-28 13:13:46 +0000272
Fred Drakee2c64912002-12-31 17:23:27 +0000273class InterpolationSyntaxError(InterpolationError):
Fred Drakea4923622010-08-09 12:52:45 +0000274 """Raised when the source text contains invalid syntax.
275
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000276 Current implementation raises this exception when the source text into
277 which substitutions are made does not conform to the required syntax.
Fred Drakea4923622010-08-09 12:52:45 +0000278 """
Neal Norwitzce1d9442002-12-30 23:38:47 +0000279
Georg Brandl96a60ae2010-07-28 13:13:46 +0000280
Fred Drakee2c64912002-12-31 17:23:27 +0000281class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000282 """Raised when substitutions are nested too deeply."""
283
Fred Drake2a37f9f2000-09-27 22:43:54 +0000284 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000285 msg = ("Value interpolation too deeply recursive:\n"
286 "\tsection: [%s]\n"
287 "\toption : %s\n"
288 "\trawval : %s\n"
289 % (section, option, rawval))
290 InterpolationError.__init__(self, option, section, msg)
Michael Foordbd6c0792010-07-25 23:09:25 +0000291 self.args = (option, section, rawval)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000292
Georg Brandl96a60ae2010-07-28 13:13:46 +0000293
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000294class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000295 """Raised when a configuration file does not follow legal syntax."""
296
Fred Drakea4923622010-08-09 12:52:45 +0000297 def __init__(self, source=None, filename=None):
298 # Exactly one of `source'/`filename' arguments has to be given.
299 # `filename' kept for compatibility.
300 if filename and source:
301 raise ValueError("Cannot specify both `filename' and `source'. "
302 "Use `source'.")
303 elif not filename and not source:
304 raise ValueError("Required argument `source' not given.")
305 elif filename:
306 source = filename
307 Error.__init__(self, 'Source contains parsing errors: %s' % source)
308 self.source = source
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000309 self.errors = []
Fred Drakea4923622010-08-09 12:52:45 +0000310 self.args = (source, )
311
312 @property
313 def filename(self):
314 """Deprecated, use `source'."""
315 warnings.warn(
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000316 "The 'filename' attribute will be removed in future versions. "
Fred Drakea4923622010-08-09 12:52:45 +0000317 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000318 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000319 )
320 return self.source
321
322 @filename.setter
323 def filename(self, value):
324 """Deprecated, user `source'."""
325 warnings.warn(
326 "The 'filename' attribute will be removed in future versions. "
327 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000328 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000329 )
330 self.source = value
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000331
332 def append(self, lineno, line):
333 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000334 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000335
Georg Brandl96a60ae2010-07-28 13:13:46 +0000336
Fred Drake2a37f9f2000-09-27 22:43:54 +0000337class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000338 """Raised when a key-value pair is found before any section header."""
339
Fred Drake2a37f9f2000-09-27 22:43:54 +0000340 def __init__(self, filename, lineno, line):
341 Error.__init__(
342 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000343 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000344 (filename, lineno, line))
Fred Drakea4923622010-08-09 12:52:45 +0000345 self.source = filename
Fred Drake2a37f9f2000-09-27 22:43:54 +0000346 self.lineno = lineno
347 self.line = line
Michael Foordbd6c0792010-07-25 23:09:25 +0000348 self.args = (filename, lineno, line)
Guido van Rossum3d209861997-12-09 16:10:31 +0000349
Georg Brandl96a60ae2010-07-28 13:13:46 +0000350
Fred Drakecc645b92010-09-04 04:35:34 +0000351# Used in parser getters to indicate the default behaviour when a specific
352# option is not found it to raise an exception. Created to enable `None' as
353# a valid fallback value.
354_UNSET = object()
355
356
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000357class Interpolation:
358 """Dummy interpolation that passes the value through with no changes."""
359
360 def before_get(self, parser, section, option, value, defaults):
361 return value
362
363 def before_set(self, parser, section, option, value):
364 return value
365
366 def before_read(self, parser, section, option, value):
367 return value
368
369 def before_write(self, parser, section, option, value):
370 return value
371
372
373class BasicInterpolation(Interpolation):
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000374 """Interpolation as implemented in the classic ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000375
376 The option values can contain format strings which refer to other values in
377 the same section, or values in the special default section.
378
379 For example:
380
381 something: %(dir)s/whatever
382
383 would resolve the "%(dir)s" to the value of dir. All reference
384 expansions are done late, on demand. If a user needs to use a bare % in
385 a configuration file, she can escape it by writing %%. Other other % usage
386 is considered a user error and raises `InterpolationSyntaxError'."""
387
388 _KEYCRE = re.compile(r"%\(([^)]+)\)s")
389
390 def before_get(self, parser, section, option, value, defaults):
391 L = []
392 self._interpolate_some(parser, option, L, value, section, defaults, 1)
393 return ''.join(L)
394
395 def before_set(self, parser, section, option, value):
396 tmp_value = value.replace('%%', '') # escaped percent signs
397 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
398 if '%' in tmp_value:
399 raise ValueError("invalid interpolation syntax in %r at "
400 "position %d" % (value, tmp_value.find('%')))
401 return value
402
403 def _interpolate_some(self, parser, option, accum, rest, section, map,
404 depth):
405 if depth > MAX_INTERPOLATION_DEPTH:
406 raise InterpolationDepthError(option, section, rest)
407 while rest:
408 p = rest.find("%")
409 if p < 0:
410 accum.append(rest)
411 return
412 if p > 0:
413 accum.append(rest[:p])
414 rest = rest[p:]
415 # p is no longer used
416 c = rest[1:2]
417 if c == "%":
418 accum.append("%")
419 rest = rest[2:]
420 elif c == "(":
421 m = self._KEYCRE.match(rest)
422 if m is None:
423 raise InterpolationSyntaxError(option, section,
424 "bad interpolation variable reference %r" % rest)
425 var = parser.optionxform(m.group(1))
426 rest = rest[m.end():]
427 try:
428 v = map[var]
429 except KeyError:
430 raise InterpolationMissingOptionError(
431 option, section, rest, var)
432 if "%" in v:
433 self._interpolate_some(parser, option, accum, v,
434 section, map, depth + 1)
435 else:
436 accum.append(v)
437 else:
438 raise InterpolationSyntaxError(
439 option, section,
440 "'%%' must be followed by '%%' or '(', "
441 "found: %r" % (rest,))
442
443
444class ExtendedInterpolation(Interpolation):
445 """Advanced variant of interpolation, supports the syntax used by
446 `zc.buildout'. Enables interpolation between sections."""
447
448 _KEYCRE = re.compile(r"\$\{([^}]+)\}")
449
450 def before_get(self, parser, section, option, value, defaults):
451 L = []
452 self._interpolate_some(parser, option, L, value, section, defaults, 1)
453 return ''.join(L)
454
455 def before_set(self, parser, section, option, value):
456 tmp_value = value.replace('$$', '') # escaped dollar signs
457 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
458 if '$' in tmp_value:
459 raise ValueError("invalid interpolation syntax in %r at "
460 "position %d" % (value, tmp_value.find('%')))
461 return value
462
463 def _interpolate_some(self, parser, option, accum, rest, section, map,
464 depth):
465 if depth > MAX_INTERPOLATION_DEPTH:
466 raise InterpolationDepthError(option, section, rest)
467 while rest:
468 p = rest.find("$")
469 if p < 0:
470 accum.append(rest)
471 return
472 if p > 0:
473 accum.append(rest[:p])
474 rest = rest[p:]
475 # p is no longer used
476 c = rest[1:2]
477 if c == "$":
478 accum.append("$")
479 rest = rest[2:]
480 elif c == "{":
481 m = self._KEYCRE.match(rest)
482 if m is None:
483 raise InterpolationSyntaxError(option, section,
484 "bad interpolation variable reference %r" % rest)
Łukasz Langae698cd52011-04-28 10:58:57 +0200485 path = m.group(1).split(':')
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000486 rest = rest[m.end():]
487 sect = section
488 opt = option
489 try:
490 if len(path) == 1:
Łukasz Langae698cd52011-04-28 10:58:57 +0200491 opt = parser.optionxform(path[0])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000492 v = map[opt]
493 elif len(path) == 2:
494 sect = path[0]
Łukasz Langae698cd52011-04-28 10:58:57 +0200495 opt = parser.optionxform(path[1])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000496 v = parser.get(sect, opt, raw=True)
497 else:
498 raise InterpolationSyntaxError(
499 option, section,
500 "More than one ':' found: %r" % (rest,))
Łukasz Langa71b37a52010-12-17 21:56:32 +0000501 except (KeyError, NoSectionError, NoOptionError):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000502 raise InterpolationMissingOptionError(
Łukasz Langa71b37a52010-12-17 21:56:32 +0000503 option, section, rest, ":".join(path))
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000504 if "$" in v:
505 self._interpolate_some(parser, opt, accum, v, sect,
506 dict(parser.items(sect, raw=True)),
507 depth + 1)
508 else:
509 accum.append(v)
510 else:
511 raise InterpolationSyntaxError(
512 option, section,
513 "'$' must be followed by '$' or '{', "
514 "found: %r" % (rest,))
515
516
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000517class LegacyInterpolation(Interpolation):
518 """Deprecated interpolation used in old versions of ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000519 Use BasicInterpolation or ExtendedInterpolation instead."""
520
521 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
522
523 def before_get(self, parser, section, option, value, vars):
524 rawval = value
525 depth = MAX_INTERPOLATION_DEPTH
526 while depth: # Loop through this until it's done
527 depth -= 1
528 if value and "%(" in value:
529 replace = functools.partial(self._interpolation_replace,
530 parser=parser)
531 value = self._KEYCRE.sub(replace, value)
532 try:
533 value = value % vars
534 except KeyError as e:
535 raise InterpolationMissingOptionError(
536 option, section, rawval, e.args[0])
537 else:
538 break
539 if value and "%(" in value:
540 raise InterpolationDepthError(option, section, rawval)
541 return value
542
543 def before_set(self, parser, section, option, value):
544 return value
545
546 @staticmethod
547 def _interpolation_replace(match, parser):
548 s = match.group(1)
549 if s is None:
550 return match.group()
551 else:
552 return "%%(%s)s" % parser.optionxform(s)
553
554
Łukasz Langa26d513c2010-11-10 18:57:39 +0000555class RawConfigParser(MutableMapping):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000556 """ConfigParser that does not do interpolation."""
557
558 # Regular expressions for parsing section headers and options
559 _SECT_TMPL = r"""
560 \[ # [
561 (?P<header>[^]]+) # very permissive!
562 \] # ]
563 """
564 _OPT_TMPL = r"""
565 (?P<option>.*?) # very permissive!
566 \s*(?P<vi>{delim})\s* # any number of space/tab,
567 # followed by any of the
568 # allowed delimiters,
569 # followed by any space/tab
570 (?P<value>.*)$ # everything up to eol
571 """
572 _OPT_NV_TMPL = r"""
573 (?P<option>.*?) # very permissive!
574 \s*(?: # any number of space/tab,
575 (?P<vi>{delim})\s* # optionally followed by
576 # any of the allowed
577 # delimiters, followed by any
578 # space/tab
579 (?P<value>.*))?$ # everything up to eol
580 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000581 # Interpolation algorithm to be used if the user does not specify another
582 _DEFAULT_INTERPOLATION = Interpolation()
Georg Brandl96a60ae2010-07-28 13:13:46 +0000583 # Compiled regular expression for matching sections
584 SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
585 # Compiled regular expression for matching options with typical separators
586 OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
587 # Compiled regular expression for matching options with optional values
588 # delimited using typical separators
589 OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
590 # Compiled regular expression for matching leading whitespace in a line
591 NONSPACECRE = re.compile(r"\S")
Fred Drakecc645b92010-09-04 04:35:34 +0000592 # Possible boolean values in the configuration.
593 BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
594 '0': False, 'no': False, 'false': False, 'off': False}
Georg Brandl96a60ae2010-07-28 13:13:46 +0000595
Fred Drake03c44a32010-02-19 06:08:41 +0000596 def __init__(self, defaults=None, dict_type=_default_dict,
Fred Drakea4923622010-08-09 12:52:45 +0000597 allow_no_value=False, *, delimiters=('=', ':'),
Łukasz Langab25a7912010-12-17 01:32:29 +0000598 comment_prefixes=('#', ';'), inline_comment_prefixes=None,
599 strict=True, empty_lines_in_values=True,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000600 default_section=DEFAULTSECT,
601 interpolation=_UNSET):
602
Thomas Wouters89f507f2006-12-13 04:49:30 +0000603 self._dict = dict_type
604 self._sections = self._dict()
605 self._defaults = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000606 self._proxies = self._dict()
Łukasz Langac264c092010-11-20 16:15:37 +0000607 self._proxies[default_section] = SectionProxy(self, default_section)
David Goodger68a1abd2004-10-03 15:40:25 +0000608 if defaults:
609 for key, value in defaults.items():
610 self._defaults[self.optionxform(key)] = value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000611 self._delimiters = tuple(delimiters)
612 if delimiters == ('=', ':'):
613 self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
614 else:
Fred Drakea4923622010-08-09 12:52:45 +0000615 d = "|".join(re.escape(d) for d in delimiters)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000616 if allow_no_value:
Fred Drakea4923622010-08-09 12:52:45 +0000617 self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000618 re.VERBOSE)
619 else:
Fred Drakea4923622010-08-09 12:52:45 +0000620 self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000621 re.VERBOSE)
Łukasz Langab25a7912010-12-17 01:32:29 +0000622 self._comment_prefixes = tuple(comment_prefixes or ())
623 self._inline_comment_prefixes = tuple(inline_comment_prefixes or ())
Fred Drakea4923622010-08-09 12:52:45 +0000624 self._strict = strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000625 self._allow_no_value = allow_no_value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000626 self._empty_lines_in_values = empty_lines_in_values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000627 self.default_section=default_section
Łukasz Langa1aa422f2011-04-28 17:03:45 +0200628 self._interpolation = interpolation
629 if self._interpolation is _UNSET:
630 self._interpolation = self._DEFAULT_INTERPOLATION
631 if self._interpolation is None:
632 self._interpolation = Interpolation()
Guido van Rossum3d209861997-12-09 16:10:31 +0000633
634 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000635 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000636
637 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000638 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000639 # self._sections will never have [DEFAULT] in it
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000640 return list(self._sections.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000641
642 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000643 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000644
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000645 Raise DuplicateSectionError if a section by the specified name
Łukasz Langac264c092010-11-20 16:15:37 +0000646 already exists. Raise ValueError if name is DEFAULT.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000647 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000648 if section == self.default_section:
Łukasz Langa3a11e712010-12-03 22:15:19 +0000649 raise ValueError('Invalid section name: %r' % section)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000650
Fred Drakefce65572002-10-25 18:08:18 +0000651 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000652 raise DuplicateSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000653 self._sections[section] = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000654 self._proxies[section] = SectionProxy(self, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000655
656 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000657 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000658
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000659 The DEFAULT section is not acknowledged.
660 """
Fred Drakefce65572002-10-25 18:08:18 +0000661 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000662
663 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000664 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000665 try:
Fred Drakefce65572002-10-25 18:08:18 +0000666 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000667 except KeyError:
668 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000669 opts.update(self._defaults)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000670 return list(opts.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000671
Georg Brandl8dcaa732010-07-29 12:17:40 +0000672 def read(self, filenames, encoding=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000673 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000674
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000675 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000676 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000677 configuration file locations (e.g. current directory, user's
678 home directory, systemwide directory), and all existing
679 configuration files in the list will be read. A single
680 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000681
682 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000683 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000684 if isinstance(filenames, str):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000685 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000686 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000687 for filename in filenames:
688 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000689 with open(filename, encoding=encoding) as fp:
690 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000691 except IOError:
692 continue
Fred Drake82903142004-05-18 04:24:02 +0000693 read_ok.append(filename)
694 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000695
Fred Drakea4923622010-08-09 12:52:45 +0000696 def read_file(self, f, source=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000697 """Like read() but the argument must be a file-like object.
698
Łukasz Langadaab1c82011-04-27 18:10:05 +0200699 The `f' argument must be iterable, returning one line at a time.
700 Optional second argument is the `source' specifying the name of the
701 file being read. If not given, it is taken from f.name. If `f' has no
702 `name' attribute, `<???>' is used.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000703 """
Fred Drakea4923622010-08-09 12:52:45 +0000704 if source is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000705 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000706 source = f.name
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000707 except AttributeError:
Fred Drakea4923622010-08-09 12:52:45 +0000708 source = '<???>'
709 self._read(f, source)
710
711 def read_string(self, string, source='<string>'):
712 """Read configuration from a given string."""
713 sfile = io.StringIO(string)
714 self.read_file(sfile, source)
715
716 def read_dict(self, dictionary, source='<dict>'):
717 """Read configuration from a dictionary.
718
719 Keys are section names, values are dictionaries with keys and values
720 that should be present in the section. If the used dictionary type
721 preserves order, sections and their keys will be added in order.
722
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000723 All types held in the dictionary are converted to strings during
724 reading, including section names, option names and keys.
725
Fred Drakea4923622010-08-09 12:52:45 +0000726 Optional second argument is the `source' specifying the name of the
727 dictionary being read.
728 """
729 elements_added = set()
730 for section, keys in dictionary.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000731 section = str(section)
Fred Drakea4923622010-08-09 12:52:45 +0000732 try:
733 self.add_section(section)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000734 except (DuplicateSectionError, ValueError):
Fred Drakea4923622010-08-09 12:52:45 +0000735 if self._strict and section in elements_added:
736 raise
Łukasz Langa71b37a52010-12-17 21:56:32 +0000737 elements_added.add(section)
Fred Drakea4923622010-08-09 12:52:45 +0000738 for key, value in keys.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000739 key = self.optionxform(str(key))
Fred Drakecc645b92010-09-04 04:35:34 +0000740 if value is not None:
741 value = str(value)
Fred Drakea4923622010-08-09 12:52:45 +0000742 if self._strict and (section, key) in elements_added:
743 raise DuplicateOptionError(section, key, source)
744 elements_added.add((section, key))
745 self.set(section, key, value)
746
747 def readfp(self, fp, filename=None):
748 """Deprecated, use read_file instead."""
749 warnings.warn(
750 "This method will be removed in future versions. "
751 "Use 'parser.read_file()' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000752 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000753 )
754 self.read_file(fp, source=filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000755
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000756 def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000757 """Get an option value for a given section.
758
759 If `vars' is provided, it must be a dictionary. The option is looked up
760 in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000761 If the key is not found and `fallback' is provided, it is used as
762 a fallback value. `None' can be provided as a `fallback' value.
763
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000764 If interpolation is enabled and the optional argument `raw' is False,
765 all interpolations are expanded in the return values.
766
767 Arguments `raw', `vars', and `fallback' are keyword only.
768
769 The section DEFAULT is special.
Fred Drakecc645b92010-09-04 04:35:34 +0000770 """
771 try:
772 d = self._unify_values(section, vars)
773 except NoSectionError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000774 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000775 raise
Fred Drakefce65572002-10-25 18:08:18 +0000776 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000777 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000778 option = self.optionxform(option)
779 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000780 value = d[option]
Fred Drakecc645b92010-09-04 04:35:34 +0000781 except KeyError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000782 if fallback is _UNSET:
Fred Drakefce65572002-10-25 18:08:18 +0000783 raise NoOptionError(option, section)
Fred Drakecc645b92010-09-04 04:35:34 +0000784 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000785 return fallback
Fred Drake2a37f9f2000-09-27 22:43:54 +0000786
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000787 if raw or value is None:
788 return value
789 else:
790 return self._interpolation.before_get(self, section, option, value,
791 d)
Fred Drake2ca041f2002-09-27 15:49:56 +0000792
Łukasz Langa26d513c2010-11-10 18:57:39 +0000793 def _get(self, section, conv, option, **kwargs):
794 return conv(self.get(section, option, **kwargs))
Guido van Rossum3d209861997-12-09 16:10:31 +0000795
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000796 def getint(self, section, option, *, raw=False, vars=None,
797 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000798 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000799 return self._get(section, int, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000800 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000801 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000802 raise
803 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000804 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000805
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000806 def getfloat(self, section, option, *, raw=False, vars=None,
807 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000808 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000809 return self._get(section, float, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000810 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000811 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000812 raise
813 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000814 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000815
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000816 def getboolean(self, section, option, *, raw=False, vars=None,
817 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000818 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000819 return self._get(section, self._convert_to_boolean, option,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000820 raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000821 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000822 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000823 raise
824 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000825 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000826
Łukasz Langa71b37a52010-12-17 21:56:32 +0000827 def items(self, section=_UNSET, raw=False, vars=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000828 """Return a list of (name, value) tuples for each option in a section.
829
830 All % interpolations are expanded in the return values, based on the
831 defaults passed into the constructor, unless the optional argument
832 `raw' is true. Additional substitutions may be provided using the
833 `vars' argument, which must be a dictionary whose contents overrides
834 any pre-existing defaults.
835
836 The section DEFAULT is special.
837 """
Łukasz Langa71b37a52010-12-17 21:56:32 +0000838 if section is _UNSET:
839 return super().items()
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000840 d = self._defaults.copy()
841 try:
842 d.update(self._sections[section])
843 except KeyError:
844 if section != self.default_section:
845 raise NoSectionError(section)
846 # Update with the entry specific variables
847 if vars:
848 for key, value in vars.items():
849 d[self.optionxform(key)] = value
Łukasz Langa24bcc612010-12-04 11:48:11 +0000850 value_getter = lambda option: self._interpolation.before_get(self,
851 section, option, d[option], d)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000852 if raw:
Łukasz Langa24bcc612010-12-04 11:48:11 +0000853 value_getter = lambda option: d[option]
854 return [(option, value_getter(option)) for option in d.keys()]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000855
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000856 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000857 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000858
Eric S. Raymond417c4892000-07-10 18:11:00 +0000859 def has_option(self, section, option):
Łukasz Langa71b37a52010-12-17 21:56:32 +0000860 """Check for the existence of a given option in a given section.
861 If the specified `section' is None or an empty string, DEFAULT is
862 assumed. If the specified `section' does not exist, returns False."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000863 if not section or section == self.default_section:
Fred Drakec2ff9052002-09-27 15:33:11 +0000864 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000865 return option in self._defaults
866 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000867 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000868 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000869 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000870 return (option in self._sections[section]
871 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000872
Fred Drake03c44a32010-02-19 06:08:41 +0000873 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000874 """Set an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000875 if value:
876 value = self._interpolation.before_set(self, section, option,
877 value)
878 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000879 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000880 else:
881 try:
Fred Drakefce65572002-10-25 18:08:18 +0000882 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000883 except KeyError:
884 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000885 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000886
Georg Brandl96a60ae2010-07-28 13:13:46 +0000887 def write(self, fp, space_around_delimiters=True):
888 """Write an .ini-format representation of the configuration state.
889
890 If `space_around_delimiters' is True (the default), delimiters
891 between keys and values are surrounded by spaces.
892 """
893 if space_around_delimiters:
894 d = " {} ".format(self._delimiters[0])
895 else:
896 d = self._delimiters[0]
Fred Drakefce65572002-10-25 18:08:18 +0000897 if self._defaults:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000898 self._write_section(fp, self.default_section,
Łukasz Langac264c092010-11-20 16:15:37 +0000899 self._defaults.items(), d)
Fred Drakefce65572002-10-25 18:08:18 +0000900 for section in self._sections:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000901 self._write_section(fp, section,
902 self._sections[section].items(), d)
903
904 def _write_section(self, fp, section_name, section_items, delimiter):
905 """Write a single section to the specified `fp'."""
906 fp.write("[{}]\n".format(section_name))
907 for key, value in section_items:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000908 value = self._interpolation.before_write(self, section_name, key,
909 value)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000910 if value is not None or not self._allow_no_value:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000911 value = delimiter + str(value).replace('\n', '\n\t')
912 else:
913 value = ""
914 fp.write("{}{}\n".format(key, value))
915 fp.write("\n")
Eric S. Raymond417c4892000-07-10 18:11:00 +0000916
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000917 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000918 """Remove an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000919 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000920 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000921 else:
922 try:
Fred Drakefce65572002-10-25 18:08:18 +0000923 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000924 except KeyError:
925 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000926 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000927 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000928 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000929 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000930 return existed
931
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000932 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000933 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000934 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000935 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000936 del self._sections[section]
Łukasz Langa49afa382010-11-11 19:53:23 +0000937 del self._proxies[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000938 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000939
Łukasz Langa26d513c2010-11-10 18:57:39 +0000940 def __getitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000941 if key != self.default_section and not self.has_section(key):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000942 raise KeyError(key)
Łukasz Langa49afa382010-11-11 19:53:23 +0000943 return self._proxies[key]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000944
945 def __setitem__(self, key, value):
946 # To conform with the mapping protocol, overwrites existing values in
947 # the section.
948
949 # XXX this is not atomic if read_dict fails at any point. Then again,
950 # no update method in configparser is atomic in this implementation.
951 self.remove_section(key)
952 self.read_dict({key: value})
953
954 def __delitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000955 if key == self.default_section:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000956 raise ValueError("Cannot remove the default section.")
957 if not self.has_section(key):
958 raise KeyError(key)
959 self.remove_section(key)
960
961 def __contains__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000962 return key == self.default_section or self.has_section(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000963
964 def __len__(self):
965 return len(self._sections) + 1 # the default section
966
967 def __iter__(self):
968 # XXX does it break when underlying container state changed?
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000969 return itertools.chain((self.default_section,), self._sections.keys())
Łukasz Langa26d513c2010-11-10 18:57:39 +0000970
Fred Drakefce65572002-10-25 18:08:18 +0000971 def _read(self, fp, fpname):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000972 """Parse a sectioned configuration file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000973
Fred Drakea4923622010-08-09 12:52:45 +0000974 Each section in a configuration file contains a header, indicated by
975 a name in square brackets (`[]'), plus key/value options, indicated by
Georg Brandl96a60ae2010-07-28 13:13:46 +0000976 `name' and `value' delimited with a specific substring (`=' or `:' by
977 default).
978
Fred Drakea4923622010-08-09 12:52:45 +0000979 Values can span multiple lines, as long as they are indented deeper
980 than the first line of the value. Depending on the parser's mode, blank
981 lines may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000982
983 Configuration files may include comments, prefixed by specific
Fred Drakea4923622010-08-09 12:52:45 +0000984 characters (`#' and `;' by default). Comments may appear on their own
985 in an otherwise empty line or may be entered in lines holding values or
Georg Brandl96a60ae2010-07-28 13:13:46 +0000986 section names.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000987 """
Fred Drakea4923622010-08-09 12:52:45 +0000988 elements_added = set()
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000989 cursect = None # None, or a dictionary
Fred Drakea4923622010-08-09 12:52:45 +0000990 sectname = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000991 optname = None
992 lineno = 0
Georg Brandl96a60ae2010-07-28 13:13:46 +0000993 indent_level = 0
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000994 e = None # None, or an exception
Georg Brandl96a60ae2010-07-28 13:13:46 +0000995 for lineno, line in enumerate(fp, start=1):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000996 comment_start = None
Georg Brandl96a60ae2010-07-28 13:13:46 +0000997 # strip inline comments
Łukasz Langab25a7912010-12-17 01:32:29 +0000998 for prefix in self._inline_comment_prefixes:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000999 index = line.find(prefix)
1000 if index == 0 or (index > 0 and line[index-1].isspace()):
1001 comment_start = index
1002 break
Łukasz Langab25a7912010-12-17 01:32:29 +00001003 # strip full line comments
1004 for prefix in self._comment_prefixes:
1005 if line.strip().startswith(prefix):
1006 comment_start = 0
1007 break
Georg Brandl96a60ae2010-07-28 13:13:46 +00001008 value = line[:comment_start].strip()
1009 if not value:
Georg Brandlf206d0e2010-07-29 11:56:20 +00001010 if self._empty_lines_in_values:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001011 # add empty line to the value, but only if there was no
1012 # comment on the line
Georg Brandlf206d0e2010-07-29 11:56:20 +00001013 if (comment_start is None and
1014 cursect is not None and
1015 optname and
1016 cursect[optname] is not None):
1017 cursect[optname].append('') # newlines added at join
Georg Brandl96a60ae2010-07-28 13:13:46 +00001018 else:
1019 # empty line marks end of value
1020 indent_level = sys.maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001021 continue
1022 # continuation line?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001023 first_nonspace = self.NONSPACECRE.search(line)
1024 cur_indent_level = first_nonspace.start() if first_nonspace else 0
1025 if (cursect is not None and optname and
1026 cur_indent_level > indent_level):
1027 cursect[optname].append(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001028 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001029 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001030 indent_level = cur_indent_level
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001031 # is it a section header?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001032 mo = self.SECTCRE.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001033 if mo:
1034 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +00001035 if sectname in self._sections:
Fred Drakea4923622010-08-09 12:52:45 +00001036 if self._strict and sectname in elements_added:
1037 raise DuplicateSectionError(sectname, fpname,
1038 lineno)
Fred Drakefce65572002-10-25 18:08:18 +00001039 cursect = self._sections[sectname]
Fred Drakea4923622010-08-09 12:52:45 +00001040 elements_added.add(sectname)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001041 elif sectname == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001042 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001043 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001044 cursect = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +00001045 self._sections[sectname] = cursect
Łukasz Langa49afa382010-11-11 19:53:23 +00001046 self._proxies[sectname] = SectionProxy(self, sectname)
Fred Drakea4923622010-08-09 12:52:45 +00001047 elements_added.add(sectname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001048 # So sections can't start with a continuation line
1049 optname = None
1050 # no section header in the file?
1051 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001052 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001053 # an option line?
1054 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001055 mo = self._optcre.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001056 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +00001057 optname, vi, optval = mo.group('option', 'vi', 'value')
Georg Brandl96a60ae2010-07-28 13:13:46 +00001058 if not optname:
1059 e = self._handle_error(e, fpname, lineno, line)
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001060 optname = self.optionxform(optname.rstrip())
Fred Drakea4923622010-08-09 12:52:45 +00001061 if (self._strict and
1062 (sectname, optname) in elements_added):
1063 raise DuplicateOptionError(sectname, optname,
1064 fpname, lineno)
1065 elements_added.add((sectname, optname))
Fred Drake03c44a32010-02-19 06:08:41 +00001066 # This check is fine because the OPTCRE cannot
1067 # match if it would set optval to None
1068 if optval is not None:
Fred Drake03c44a32010-02-19 06:08:41 +00001069 optval = optval.strip()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001070 cursect[optname] = [optval]
1071 else:
1072 # valueless option handling
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001073 cursect[optname] = None
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001074 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001075 # a non-fatal parsing error occurred. set up the
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001076 # exception but keep going. the exception will be
1077 # raised at the end of the file and will contain a
1078 # list of all bogus lines
Georg Brandl96a60ae2010-07-28 13:13:46 +00001079 e = self._handle_error(e, fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001080 # if any parsing errors occurred, raise an exception
1081 if e:
1082 raise e
Georg Brandl96a60ae2010-07-28 13:13:46 +00001083 self._join_multiline_values()
Fred Drakefce65572002-10-25 18:08:18 +00001084
Georg Brandl96a60ae2010-07-28 13:13:46 +00001085 def _join_multiline_values(self):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001086 defaults = self.default_section, self._defaults
1087 all_sections = itertools.chain((defaults,),
1088 self._sections.items())
1089 for section, options in all_sections:
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001090 for name, val in options.items():
1091 if isinstance(val, list):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001092 val = '\n'.join(val).rstrip()
1093 options[name] = self._interpolation.before_read(self,
1094 section,
1095 name, val)
Fred Drakefce65572002-10-25 18:08:18 +00001096
Georg Brandl96a60ae2010-07-28 13:13:46 +00001097 def _handle_error(self, exc, fpname, lineno, line):
1098 if not exc:
1099 exc = ParsingError(fpname)
1100 exc.append(lineno, repr(line))
1101 return exc
1102
Fred Drakecc645b92010-09-04 04:35:34 +00001103 def _unify_values(self, section, vars):
Raymond Hettingerddb52402011-02-21 19:42:11 +00001104 """Create a sequence of lookups with 'vars' taking priority over
1105 the 'section' which takes priority over the DEFAULTSECT.
1106
Fred Drakefce65572002-10-25 18:08:18 +00001107 """
Raymond Hettingerddb52402011-02-21 19:42:11 +00001108 sectiondict = {}
Fred Drakefce65572002-10-25 18:08:18 +00001109 try:
Raymond Hettingerddb52402011-02-21 19:42:11 +00001110 sectiondict = self._sections[section]
Fred Drakefce65572002-10-25 18:08:18 +00001111 except KeyError:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001112 if section != self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001113 raise NoSectionError(section)
1114 # Update with the entry specific variables
Raymond Hettingerddb52402011-02-21 19:42:11 +00001115 vardict = {}
David Goodger68a1abd2004-10-03 15:40:25 +00001116 if vars:
1117 for key, value in vars.items():
Fred Drakecc645b92010-09-04 04:35:34 +00001118 if value is not None:
1119 value = str(value)
Raymond Hettingerddb52402011-02-21 19:42:11 +00001120 vardict[self.optionxform(key)] = value
1121 return _ChainMap(vardict, sectiondict, self._defaults)
Fred Drakecc645b92010-09-04 04:35:34 +00001122
1123 def _convert_to_boolean(self, value):
1124 """Return a boolean value translating from other types if necessary.
1125 """
1126 if value.lower() not in self.BOOLEAN_STATES:
1127 raise ValueError('Not a boolean: %s' % value)
1128 return self.BOOLEAN_STATES[value.lower()]
1129
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001130 def _validate_value_types(self, *, section="", option="", value=""):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001131 """Raises a TypeError for non-string values.
1132
1133 The only legal non-string value if we allow valueless
1134 options is None, so we need to check if the value is a
1135 string if:
1136 - we do not allow valueless options, or
1137 - we allow valueless options but the value is not None
1138
1139 For compatibility reasons this method is not used in classic set()
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001140 for RawConfigParsers. It is invoked in every case for mapping protocol
1141 access and in ConfigParser.set().
Łukasz Langa26d513c2010-11-10 18:57:39 +00001142 """
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001143 if not isinstance(section, str):
1144 raise TypeError("section names must be strings")
1145 if not isinstance(option, str):
1146 raise TypeError("option keys must be strings")
Łukasz Langa26d513c2010-11-10 18:57:39 +00001147 if not self._allow_no_value or value:
1148 if not isinstance(value, str):
1149 raise TypeError("option values must be strings")
1150
1151
Fred Drakecc645b92010-09-04 04:35:34 +00001152class ConfigParser(RawConfigParser):
1153 """ConfigParser implementing interpolation."""
1154
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001155 _DEFAULT_INTERPOLATION = BasicInterpolation()
David Goodger1cbf2062004-10-03 15:55:09 +00001156
Fred Drake03c44a32010-02-19 06:08:41 +00001157 def set(self, section, option, value=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001158 """Set an option. Extends RawConfigParser.set by validating type and
1159 interpolation syntax on the value."""
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001160 self._validate_value_types(option=option, value=value)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001161 super().set(section, option, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001162
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001163 def add_section(self, section):
1164 """Create a new section in the configuration. Extends
1165 RawConfigParser.add_section by validating if the section name is
1166 a string."""
1167 self._validate_value_types(section=section)
1168 super().add_section(section)
1169
Łukasz Langa26d513c2010-11-10 18:57:39 +00001170
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001171class SafeConfigParser(ConfigParser):
1172 """ConfigParser alias for backwards compatibility purposes."""
1173
1174 def __init__(self, *args, **kwargs):
1175 super().__init__(*args, **kwargs)
1176 warnings.warn(
1177 "The SafeConfigParser class has been renamed to ConfigParser "
1178 "in Python 3.2. This alias will be removed in future versions."
1179 " Use ConfigParser directly instead.",
1180 DeprecationWarning, stacklevel=2
1181 )
1182
1183
Łukasz Langa26d513c2010-11-10 18:57:39 +00001184class SectionProxy(MutableMapping):
1185 """A proxy for a single section from a parser."""
1186
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001187 def __init__(self, parser, name):
1188 """Creates a view on a section of the specified `name` in `parser`."""
Łukasz Langa26d513c2010-11-10 18:57:39 +00001189 self._parser = parser
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001190 self._name = name
Łukasz Langa26d513c2010-11-10 18:57:39 +00001191
1192 def __repr__(self):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001193 return '<Section: {}>'.format(self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001194
1195 def __getitem__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001196 if not self._parser.has_option(self._name, key):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001197 raise KeyError(key)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001198 return self._parser.get(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001199
1200 def __setitem__(self, key, value):
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001201 self._parser._validate_value_types(option=key, value=value)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001202 return self._parser.set(self._name, key, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001203
1204 def __delitem__(self, key):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001205 if not (self._parser.has_option(self._name, key) and
1206 self._parser.remove_option(self._name, key)):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001207 raise KeyError(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001208
1209 def __contains__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001210 return self._parser.has_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001211
1212 def __len__(self):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001213 return len(self._options())
Łukasz Langa26d513c2010-11-10 18:57:39 +00001214
1215 def __iter__(self):
Łukasz Langa71b37a52010-12-17 21:56:32 +00001216 return self._options().__iter__()
1217
1218 def _options(self):
1219 if self._name != self._parser.default_section:
1220 return self._parser.options(self._name)
1221 else:
1222 return self._parser.defaults()
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001223
Łukasz Langa2f0fd0f2010-12-04 17:48:18 +00001224 def get(self, option, fallback=None, *, raw=False, vars=None):
1225 return self._parser.get(self._name, option, raw=raw, vars=vars,
1226 fallback=fallback)
1227
1228 def getint(self, option, fallback=None, *, raw=False, vars=None):
1229 return self._parser.getint(self._name, option, raw=raw, vars=vars,
1230 fallback=fallback)
1231
1232 def getfloat(self, option, fallback=None, *, raw=False, vars=None):
1233 return self._parser.getfloat(self._name, option, raw=raw, vars=vars,
1234 fallback=fallback)
1235
1236 def getboolean(self, option, fallback=None, *, raw=False, vars=None):
1237 return self._parser.getboolean(self._name, option, raw=raw, vars=vars,
1238 fallback=fallback)
1239
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001240 @property
1241 def parser(self):
1242 # The parser object of the proxy is read-only.
1243 return self._parser
1244
1245 @property
1246 def name(self):
1247 # The name of the section on a proxy is read-only.
1248 return self._name