blob: b5623cdbad9615ebf7211c430fe8cd33a7ebf177 [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 Langab6a6f5f2010-12-03 16:28:00 +00008SafeConfigParser constructor as a dictionary.
Guido van Rossum3d209861997-12-09 16:10:31 +00009
10class:
11
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000012SafeConfigParser -- responsible for parsing a list of
13 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,
18 delimiters=('=', ':'), comment_prefixes=_COMPATIBLE,
19 strict=False, empty_lines_in_values=True):
Georg Brandl96a60ae2010-07-28 13:13:46 +000020 Create the parser. When `defaults' is given, it is initialized into the
21 dictionary or intrinsic defaults. The keys must be strings, the values
Łukasz Langa5c863392010-11-21 13:41:35 +000022 must be appropriate for %()s string interpolation.
Georg Brandl96a60ae2010-07-28 13:13:46 +000023
24 When `dict_type' is given, it will be used to create the dictionary
25 objects for the list of sections, for the options within a section, and
26 for the default values.
27
28 When `delimiters' is given, it will be used as the set of substrings
29 that divide keys from values.
30
31 When `comment_prefixes' is given, it will be used as the set of
32 substrings that prefix comments in a line.
33
Fred Drakea4923622010-08-09 12:52:45 +000034 When `strict` is True, the parser won't allow for any section or option
35 duplicates while reading from a single source (file, string or
36 dictionary). Default is False.
37
Georg Brandl96a60ae2010-07-28 13:13:46 +000038 When `empty_lines_in_values' is False (default: True), each empty line
39 marks the end of an option. Otherwise, internal empty lines of
40 a multiline option are kept as part of the value.
41
42 When `allow_no_value' is True (default: False), options without
43 values are accepted; the value presented for these is None.
Guido van Rossum3d209861997-12-09 16:10:31 +000044
Barry Warsawf09f6a51999-01-26 22:01:37 +000045 sections()
Georg Brandl96a60ae2010-07-28 13:13:46 +000046 Return all the configuration section names, sans DEFAULT.
Guido van Rossum3d209861997-12-09 16:10:31 +000047
Guido van Rossuma5a24b71999-10-04 19:58:22 +000048 has_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000049 Return whether the given section exists.
Guido van Rossuma5a24b71999-10-04 19:58:22 +000050
Eric S. Raymond649685a2000-07-14 14:28:22 +000051 has_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +000052 Return whether the given option exists in the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +000053
Barry Warsawf09f6a51999-01-26 22:01:37 +000054 options(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000055 Return list of configuration options for the named section.
Guido van Rossum3d209861997-12-09 16:10:31 +000056
Georg Brandl8dcaa732010-07-29 12:17:40 +000057 read(filenames, encoding=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000058 Read and parse the list of named configuration files, given by
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000059 name. A single filename is also allowed. Non-existing files
Fred Drake82903142004-05-18 04:24:02 +000060 are ignored. Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000061
Fred Drakea4923622010-08-09 12:52:45 +000062 read_file(f, filename=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000063 Read and parse one configuration file, given as a file object.
Fred Drakea4923622010-08-09 12:52:45 +000064 The filename defaults to f.name; it is only used in error
65 messages (if f has no `name' attribute, the string `<???>' is used).
66
67 read_string(string)
68 Read configuration from a given string.
69
70 read_dict(dictionary)
71 Read configuration from a dictionary. Keys are section names,
72 values are dictionaries with keys and values that should be present
73 in the section. If the used dictionary type preserves order, sections
Fred Drakecc645b92010-09-04 04:35:34 +000074 and their keys will be added in order. Values are automatically
75 converted to strings.
Guido van Rossum3d209861997-12-09 16:10:31 +000076
Łukasz Langa26d513c2010-11-10 18:57:39 +000077 get(section, option, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000078 Return a string value for the named option. All % interpolations are
Barry Warsawf09f6a51999-01-26 22:01:37 +000079 expanded in the return values, based on the defaults passed into the
80 constructor and the DEFAULT section. Additional substitutions may be
81 provided using the `vars' argument, which must be a dictionary whose
Fred Drakecc645b92010-09-04 04:35:34 +000082 contents override any pre-existing defaults. If `option' is a key in
83 `vars', the value from `vars' is used.
Guido van Rossum3d209861997-12-09 16:10:31 +000084
Łukasz Langa26d513c2010-11-10 18:57:39 +000085 getint(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000086 Like get(), but convert value to an integer.
Guido van Rossum3d209861997-12-09 16:10:31 +000087
Łukasz Langa26d513c2010-11-10 18:57:39 +000088 getfloat(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000089 Like get(), but convert value to a float.
Guido van Rossum3d209861997-12-09 16:10:31 +000090
Łukasz Langa26d513c2010-11-10 18:57:39 +000091 getboolean(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000092 Like get(), but convert value to a boolean (currently case
Neal Norwitzf680cc42002-12-17 01:56:47 +000093 insensitively defined as 0, false, no, off for False, and 1, true,
94 yes, on for True). Returns False or True.
Eric S. Raymond649685a2000-07-14 14:28:22 +000095
Neal Norwitzf680cc42002-12-17 01:56:47 +000096 items(section, raw=False, vars=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000097 Return a list of tuples with (name, value) for each option
Fred Drake2ca041f2002-09-27 15:49:56 +000098 in the section.
99
Eric S. Raymond649685a2000-07-14 14:28:22 +0000100 remove_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000101 Remove the given file section and all its options.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000102
103 remove_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000104 Remove the given option from the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000105
106 set(section, option, value)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000107 Set the given option.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000108
Georg Brandl96a60ae2010-07-28 13:13:46 +0000109 write(fp, space_around_delimiters=True)
110 Write the configuration state in .ini format. If
111 `space_around_delimiters' is True (the default), delimiters
112 between keys and values are surrounded by spaces.
Guido van Rossum3d209861997-12-09 16:10:31 +0000113"""
114
Łukasz Langa26d513c2010-11-10 18:57:39 +0000115from collections import MutableMapping, OrderedDict as _default_dict
116import functools
Fred Drakea4923622010-08-09 12:52:45 +0000117import io
Łukasz Langa26d513c2010-11-10 18:57:39 +0000118import itertools
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000119import re
Georg Brandl96a60ae2010-07-28 13:13:46 +0000120import sys
Fred Drakea4923622010-08-09 12:52:45 +0000121import warnings
Guido van Rossum3d209861997-12-09 16:10:31 +0000122
Fred Drakea4923622010-08-09 12:52:45 +0000123__all__ = ["NoSectionError", "DuplicateOptionError", "DuplicateSectionError",
124 "NoOptionError", "InterpolationError", "InterpolationDepthError",
Fred Drake8d5dd982002-12-30 23:51:45 +0000125 "InterpolationSyntaxError", "ParsingError",
David Goodger1cbf2062004-10-03 15:55:09 +0000126 "MissingSectionHeaderError",
127 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +0000128 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000129
Guido van Rossum3d209861997-12-09 16:10:31 +0000130DEFAULTSECT = "DEFAULT"
131
Fred Drake2a37f9f2000-09-27 22:43:54 +0000132MAX_INTERPOLATION_DEPTH = 10
133
Guido van Rossum3d209861997-12-09 16:10:31 +0000134
Tim Peters88869f92001-01-14 23:36:06 +0000135
Guido van Rossum3d209861997-12-09 16:10:31 +0000136# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000137class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000138 """Base class for ConfigParser exceptions."""
139
Guido van Rossum360e4b82007-05-14 22:51:27 +0000140 def _get_message(self):
141 """Getter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000142 BaseException.
143 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000144 return self.__message
145
146 def _set_message(self, value):
147 """Setter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000148 BaseException.
149 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000150 self.__message = value
151
152 # BaseException.message has been deprecated since Python 2.6. To prevent
Fred Drakea4923622010-08-09 12:52:45 +0000153 # DeprecationWarning from popping up over this pre-existing attribute, use
154 # a new property that takes lookup precedence.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000155 message = property(_get_message, _set_message)
156
Guido van Rossum3d209861997-12-09 16:10:31 +0000157 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000158 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000159 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000160
Guido van Rossum3d209861997-12-09 16:10:31 +0000161 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000162 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000163
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000164 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000165
Georg Brandl96a60ae2010-07-28 13:13:46 +0000166
Guido van Rossum3d209861997-12-09 16:10:31 +0000167class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000168 """Raised when no section matches a requested option."""
169
Guido van Rossum3d209861997-12-09 16:10:31 +0000170 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000171 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000172 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000173 self.args = (section, )
Guido van Rossum3d209861997-12-09 16:10:31 +0000174
Georg Brandl96a60ae2010-07-28 13:13:46 +0000175
Guido van Rossum3d209861997-12-09 16:10:31 +0000176class DuplicateSectionError(Error):
Fred Drakea4923622010-08-09 12:52:45 +0000177 """Raised when a section is repeated in an input source.
Fred Drake8d5dd982002-12-30 23:51:45 +0000178
Fred Drakea4923622010-08-09 12:52:45 +0000179 Possible repetitions that raise this exception are: multiple creation
180 using the API or in strict parsers when a section is found more than once
181 in a single input file, string or dictionary.
182 """
183
184 def __init__(self, section, source=None, lineno=None):
185 msg = [repr(section), " already exists"]
186 if source is not None:
187 message = ["While reading from ", source]
188 if lineno is not None:
189 message.append(" [line {0:2d}]".format(lineno))
190 message.append(": section ")
191 message.extend(msg)
192 msg = message
193 else:
194 msg.insert(0, "Section ")
195 Error.__init__(self, "".join(msg))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000196 self.section = section
Fred Drakea4923622010-08-09 12:52:45 +0000197 self.source = source
198 self.lineno = lineno
199 self.args = (section, source, lineno)
200
201
202class DuplicateOptionError(Error):
203 """Raised by strict parsers when an option is repeated in an input source.
204
205 Current implementation raises this exception only when an option is found
206 more than once in a single file, string or dictionary.
207 """
208
209 def __init__(self, section, option, source=None, lineno=None):
210 msg = [repr(option), " in section ", repr(section),
211 " already exists"]
212 if source is not None:
213 message = ["While reading from ", source]
214 if lineno is not None:
215 message.append(" [line {0:2d}]".format(lineno))
216 message.append(": option ")
217 message.extend(msg)
218 msg = message
219 else:
220 msg.insert(0, "Option ")
221 Error.__init__(self, "".join(msg))
222 self.section = section
223 self.option = option
224 self.source = source
225 self.lineno = lineno
226 self.args = (section, option, source, lineno)
Guido van Rossum3d209861997-12-09 16:10:31 +0000227
Georg Brandl96a60ae2010-07-28 13:13:46 +0000228
Guido van Rossum3d209861997-12-09 16:10:31 +0000229class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000230 """A requested option was not found."""
231
Guido van Rossum3d209861997-12-09 16:10:31 +0000232 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000233 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000234 (option, section))
235 self.option = option
236 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000237 self.args = (option, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000238
Georg Brandl96a60ae2010-07-28 13:13:46 +0000239
Guido van Rossum3d209861997-12-09 16:10:31 +0000240class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000241 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000242
Fred Drakee2c64912002-12-31 17:23:27 +0000243 def __init__(self, option, section, msg):
244 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000245 self.option = option
246 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000247 self.args = (option, section, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000248
Georg Brandl96a60ae2010-07-28 13:13:46 +0000249
Fred Drakee2c64912002-12-31 17:23:27 +0000250class InterpolationMissingOptionError(InterpolationError):
251 """A string substitution required a setting which was not available."""
252
253 def __init__(self, option, section, rawval, reference):
254 msg = ("Bad value substitution:\n"
255 "\tsection: [%s]\n"
256 "\toption : %s\n"
257 "\tkey : %s\n"
258 "\trawval : %s\n"
259 % (section, option, reference, rawval))
260 InterpolationError.__init__(self, option, section, msg)
261 self.reference = reference
Michael Foordbd6c0792010-07-25 23:09:25 +0000262 self.args = (option, section, rawval, reference)
Fred Drakee2c64912002-12-31 17:23:27 +0000263
Georg Brandl96a60ae2010-07-28 13:13:46 +0000264
Fred Drakee2c64912002-12-31 17:23:27 +0000265class InterpolationSyntaxError(InterpolationError):
Fred Drakea4923622010-08-09 12:52:45 +0000266 """Raised when the source text contains invalid syntax.
267
268 Current implementation raises this exception only for SafeConfigParser
269 instances when the source text into which substitutions are made
270 does not conform to the required syntax.
271 """
Neal Norwitzce1d9442002-12-30 23:38:47 +0000272
Georg Brandl96a60ae2010-07-28 13:13:46 +0000273
Fred Drakee2c64912002-12-31 17:23:27 +0000274class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000275 """Raised when substitutions are nested too deeply."""
276
Fred Drake2a37f9f2000-09-27 22:43:54 +0000277 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000278 msg = ("Value interpolation too deeply recursive:\n"
279 "\tsection: [%s]\n"
280 "\toption : %s\n"
281 "\trawval : %s\n"
282 % (section, option, rawval))
283 InterpolationError.__init__(self, option, section, msg)
Michael Foordbd6c0792010-07-25 23:09:25 +0000284 self.args = (option, section, rawval)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000285
Georg Brandl96a60ae2010-07-28 13:13:46 +0000286
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000287class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000288 """Raised when a configuration file does not follow legal syntax."""
289
Fred Drakea4923622010-08-09 12:52:45 +0000290 def __init__(self, source=None, filename=None):
291 # Exactly one of `source'/`filename' arguments has to be given.
292 # `filename' kept for compatibility.
293 if filename and source:
294 raise ValueError("Cannot specify both `filename' and `source'. "
295 "Use `source'.")
296 elif not filename and not source:
297 raise ValueError("Required argument `source' not given.")
298 elif filename:
299 source = filename
300 Error.__init__(self, 'Source contains parsing errors: %s' % source)
301 self.source = source
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000302 self.errors = []
Fred Drakea4923622010-08-09 12:52:45 +0000303 self.args = (source, )
304
305 @property
306 def filename(self):
307 """Deprecated, use `source'."""
308 warnings.warn(
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000309 "The 'filename' attribute will be removed in future versions. "
Fred Drakea4923622010-08-09 12:52:45 +0000310 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000311 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000312 )
313 return self.source
314
315 @filename.setter
316 def filename(self, value):
317 """Deprecated, user `source'."""
318 warnings.warn(
319 "The 'filename' attribute will be removed in future versions. "
320 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000321 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000322 )
323 self.source = value
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000324
325 def append(self, lineno, line):
326 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000327 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000328
Georg Brandl96a60ae2010-07-28 13:13:46 +0000329
Fred Drake2a37f9f2000-09-27 22:43:54 +0000330class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000331 """Raised when a key-value pair is found before any section header."""
332
Fred Drake2a37f9f2000-09-27 22:43:54 +0000333 def __init__(self, filename, lineno, line):
334 Error.__init__(
335 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000336 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000337 (filename, lineno, line))
Fred Drakea4923622010-08-09 12:52:45 +0000338 self.source = filename
Fred Drake2a37f9f2000-09-27 22:43:54 +0000339 self.lineno = lineno
340 self.line = line
Michael Foordbd6c0792010-07-25 23:09:25 +0000341 self.args = (filename, lineno, line)
Guido van Rossum3d209861997-12-09 16:10:31 +0000342
Georg Brandl96a60ae2010-07-28 13:13:46 +0000343
Fred Drakecc645b92010-09-04 04:35:34 +0000344# Used in parsers to denote selecting a backwards-compatible inline comment
345# character behavior (; and # are comments at the start of a line, but ; only
346# inline)
347_COMPATIBLE = object()
348
349# Used in parser getters to indicate the default behaviour when a specific
350# option is not found it to raise an exception. Created to enable `None' as
351# a valid fallback value.
352_UNSET = object()
353
354
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000355class Interpolation:
356 """Dummy interpolation that passes the value through with no changes."""
357
358 def before_get(self, parser, section, option, value, defaults):
359 return value
360
361 def before_set(self, parser, section, option, value):
362 return value
363
364 def before_read(self, parser, section, option, value):
365 return value
366
367 def before_write(self, parser, section, option, value):
368 return value
369
370
371class BasicInterpolation(Interpolation):
372 """Interpolation as implemented in the classic SafeConfigParser.
373
374 The option values can contain format strings which refer to other values in
375 the same section, or values in the special default section.
376
377 For example:
378
379 something: %(dir)s/whatever
380
381 would resolve the "%(dir)s" to the value of dir. All reference
382 expansions are done late, on demand. If a user needs to use a bare % in
383 a configuration file, she can escape it by writing %%. Other other % usage
384 is considered a user error and raises `InterpolationSyntaxError'."""
385
386 _KEYCRE = re.compile(r"%\(([^)]+)\)s")
387
388 def before_get(self, parser, section, option, value, defaults):
389 L = []
390 self._interpolate_some(parser, option, L, value, section, defaults, 1)
391 return ''.join(L)
392
393 def before_set(self, parser, section, option, value):
394 tmp_value = value.replace('%%', '') # escaped percent signs
395 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
396 if '%' in tmp_value:
397 raise ValueError("invalid interpolation syntax in %r at "
398 "position %d" % (value, tmp_value.find('%')))
399 return value
400
401 def _interpolate_some(self, parser, option, accum, rest, section, map,
402 depth):
403 if depth > MAX_INTERPOLATION_DEPTH:
404 raise InterpolationDepthError(option, section, rest)
405 while rest:
406 p = rest.find("%")
407 if p < 0:
408 accum.append(rest)
409 return
410 if p > 0:
411 accum.append(rest[:p])
412 rest = rest[p:]
413 # p is no longer used
414 c = rest[1:2]
415 if c == "%":
416 accum.append("%")
417 rest = rest[2:]
418 elif c == "(":
419 m = self._KEYCRE.match(rest)
420 if m is None:
421 raise InterpolationSyntaxError(option, section,
422 "bad interpolation variable reference %r" % rest)
423 var = parser.optionxform(m.group(1))
424 rest = rest[m.end():]
425 try:
426 v = map[var]
427 except KeyError:
428 raise InterpolationMissingOptionError(
429 option, section, rest, var)
430 if "%" in v:
431 self._interpolate_some(parser, option, accum, v,
432 section, map, depth + 1)
433 else:
434 accum.append(v)
435 else:
436 raise InterpolationSyntaxError(
437 option, section,
438 "'%%' must be followed by '%%' or '(', "
439 "found: %r" % (rest,))
440
441
442class ExtendedInterpolation(Interpolation):
443 """Advanced variant of interpolation, supports the syntax used by
444 `zc.buildout'. Enables interpolation between sections."""
445
446 _KEYCRE = re.compile(r"\$\{([^}]+)\}")
447
448 def before_get(self, parser, section, option, value, defaults):
449 L = []
450 self._interpolate_some(parser, option, L, value, section, defaults, 1)
451 return ''.join(L)
452
453 def before_set(self, parser, section, option, value):
454 tmp_value = value.replace('$$', '') # escaped dollar signs
455 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
456 if '$' in tmp_value:
457 raise ValueError("invalid interpolation syntax in %r at "
458 "position %d" % (value, tmp_value.find('%')))
459 return value
460
461 def _interpolate_some(self, parser, option, accum, rest, section, map,
462 depth):
463 if depth > MAX_INTERPOLATION_DEPTH:
464 raise InterpolationDepthError(option, section, rest)
465 while rest:
466 p = rest.find("$")
467 if p < 0:
468 accum.append(rest)
469 return
470 if p > 0:
471 accum.append(rest[:p])
472 rest = rest[p:]
473 # p is no longer used
474 c = rest[1:2]
475 if c == "$":
476 accum.append("$")
477 rest = rest[2:]
478 elif c == "{":
479 m = self._KEYCRE.match(rest)
480 if m is None:
481 raise InterpolationSyntaxError(option, section,
482 "bad interpolation variable reference %r" % rest)
483 path = parser.optionxform(m.group(1)).split(':')
484 rest = rest[m.end():]
485 sect = section
486 opt = option
487 try:
488 if len(path) == 1:
489 opt = path[0]
490 v = map[opt]
491 elif len(path) == 2:
492 sect = path[0]
493 opt = path[1]
494 v = parser.get(sect, opt, raw=True)
495 else:
496 raise InterpolationSyntaxError(
497 option, section,
498 "More than one ':' found: %r" % (rest,))
499 except KeyError:
500 raise InterpolationMissingOptionError(
501 option, section, rest, var)
502 if "$" in v:
503 self._interpolate_some(parser, opt, accum, v, sect,
504 dict(parser.items(sect, raw=True)),
505 depth + 1)
506 else:
507 accum.append(v)
508 else:
509 raise InterpolationSyntaxError(
510 option, section,
511 "'$' must be followed by '$' or '{', "
512 "found: %r" % (rest,))
513
514
515class BrokenInterpolation(Interpolation):
516 """Deprecated interpolation as implemented in the classic ConfigParser.
517 Use BasicInterpolation or ExtendedInterpolation instead."""
518
519 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
520
521 def before_get(self, parser, section, option, value, vars):
522 rawval = value
523 depth = MAX_INTERPOLATION_DEPTH
524 while depth: # Loop through this until it's done
525 depth -= 1
526 if value and "%(" in value:
527 replace = functools.partial(self._interpolation_replace,
528 parser=parser)
529 value = self._KEYCRE.sub(replace, value)
530 try:
531 value = value % vars
532 except KeyError as e:
533 raise InterpolationMissingOptionError(
534 option, section, rawval, e.args[0])
535 else:
536 break
537 if value and "%(" in value:
538 raise InterpolationDepthError(option, section, rawval)
539 return value
540
541 def before_set(self, parser, section, option, value):
542 return value
543
544 @staticmethod
545 def _interpolation_replace(match, parser):
546 s = match.group(1)
547 if s is None:
548 return match.group()
549 else:
550 return "%%(%s)s" % parser.optionxform(s)
551
552
Łukasz Langa26d513c2010-11-10 18:57:39 +0000553class RawConfigParser(MutableMapping):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000554 """ConfigParser that does not do interpolation."""
555
556 # Regular expressions for parsing section headers and options
557 _SECT_TMPL = r"""
558 \[ # [
559 (?P<header>[^]]+) # very permissive!
560 \] # ]
561 """
562 _OPT_TMPL = r"""
563 (?P<option>.*?) # very permissive!
564 \s*(?P<vi>{delim})\s* # any number of space/tab,
565 # followed by any of the
566 # allowed delimiters,
567 # followed by any space/tab
568 (?P<value>.*)$ # everything up to eol
569 """
570 _OPT_NV_TMPL = r"""
571 (?P<option>.*?) # very permissive!
572 \s*(?: # any number of space/tab,
573 (?P<vi>{delim})\s* # optionally followed by
574 # any of the allowed
575 # delimiters, followed by any
576 # space/tab
577 (?P<value>.*))?$ # everything up to eol
578 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000579 # Interpolation algorithm to be used if the user does not specify another
580 _DEFAULT_INTERPOLATION = Interpolation()
Georg Brandl96a60ae2010-07-28 13:13:46 +0000581 # Compiled regular expression for matching sections
582 SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
583 # Compiled regular expression for matching options with typical separators
584 OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
585 # Compiled regular expression for matching options with optional values
586 # delimited using typical separators
587 OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
588 # Compiled regular expression for matching leading whitespace in a line
589 NONSPACECRE = re.compile(r"\S")
Fred Drakecc645b92010-09-04 04:35:34 +0000590 # Possible boolean values in the configuration.
591 BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
592 '0': False, 'no': False, 'false': False, 'off': False}
Georg Brandl96a60ae2010-07-28 13:13:46 +0000593
Fred Drake03c44a32010-02-19 06:08:41 +0000594 def __init__(self, defaults=None, dict_type=_default_dict,
Fred Drakea4923622010-08-09 12:52:45 +0000595 allow_no_value=False, *, delimiters=('=', ':'),
596 comment_prefixes=_COMPATIBLE, strict=False,
Łukasz Langac264c092010-11-20 16:15:37 +0000597 empty_lines_in_values=True,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000598 default_section=DEFAULTSECT,
599 interpolation=_UNSET):
600
601 if self.__class__ is RawConfigParser:
602 warnings.warn(
603 "The RawConfigParser class will be removed in future versions."
604 " Use 'SafeConfigParser(interpolation=None)' instead.",
605 DeprecationWarning, stacklevel=2
606 )
Thomas Wouters89f507f2006-12-13 04:49:30 +0000607 self._dict = dict_type
608 self._sections = self._dict()
609 self._defaults = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000610 self._proxies = self._dict()
Łukasz Langac264c092010-11-20 16:15:37 +0000611 self._proxies[default_section] = SectionProxy(self, default_section)
David Goodger68a1abd2004-10-03 15:40:25 +0000612 if defaults:
613 for key, value in defaults.items():
614 self._defaults[self.optionxform(key)] = value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000615 self._delimiters = tuple(delimiters)
616 if delimiters == ('=', ':'):
617 self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
618 else:
Fred Drakea4923622010-08-09 12:52:45 +0000619 d = "|".join(re.escape(d) for d in delimiters)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000620 if allow_no_value:
Fred Drakea4923622010-08-09 12:52:45 +0000621 self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000622 re.VERBOSE)
623 else:
Fred Drakea4923622010-08-09 12:52:45 +0000624 self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000625 re.VERBOSE)
Fred Drakecc645b92010-09-04 04:35:34 +0000626 if comment_prefixes is _COMPATIBLE:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000627 self._startonly_comment_prefixes = ('#',)
628 self._comment_prefixes = (';',)
629 else:
630 self._startonly_comment_prefixes = ()
631 self._comment_prefixes = tuple(comment_prefixes or ())
Fred Drakea4923622010-08-09 12:52:45 +0000632 self._strict = strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000633 self._allow_no_value = allow_no_value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000634 self._empty_lines_in_values = empty_lines_in_values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000635 if interpolation is _UNSET:
636 self._interpolation = self._DEFAULT_INTERPOLATION
637 else:
638 self._interpolation = interpolation
639 self.default_section=default_section
Guido van Rossum3d209861997-12-09 16:10:31 +0000640
641 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000642 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000643
644 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000645 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000646 # self._sections will never have [DEFAULT] in it
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000647 return list(self._sections.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000648
649 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000650 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000651
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000652 Raise DuplicateSectionError if a section by the specified name
Łukasz Langac264c092010-11-20 16:15:37 +0000653 already exists. Raise ValueError if name is DEFAULT.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000654 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000655 if section == self.default_section:
Łukasz Langa3a11e712010-12-03 22:15:19 +0000656 raise ValueError('Invalid section name: %r' % section)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000657
Fred Drakefce65572002-10-25 18:08:18 +0000658 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000659 raise DuplicateSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000660 self._sections[section] = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000661 self._proxies[section] = SectionProxy(self, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000662
663 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000664 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000665
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000666 The DEFAULT section is not acknowledged.
667 """
Fred Drakefce65572002-10-25 18:08:18 +0000668 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000669
670 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000671 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000672 try:
Fred Drakefce65572002-10-25 18:08:18 +0000673 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000674 except KeyError:
675 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000676 opts.update(self._defaults)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000677 return list(opts.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000678
Georg Brandl8dcaa732010-07-29 12:17:40 +0000679 def read(self, filenames, encoding=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000680 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000681
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000682 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000683 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000684 configuration file locations (e.g. current directory, user's
685 home directory, systemwide directory), and all existing
686 configuration files in the list will be read. A single
687 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000688
689 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000690 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000691 if isinstance(filenames, str):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000692 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000693 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000694 for filename in filenames:
695 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000696 with open(filename, encoding=encoding) as fp:
697 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000698 except IOError:
699 continue
Fred Drake82903142004-05-18 04:24:02 +0000700 read_ok.append(filename)
701 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000702
Fred Drakea4923622010-08-09 12:52:45 +0000703 def read_file(self, f, source=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000704 """Like read() but the argument must be a file-like object.
705
Fred Drakea4923622010-08-09 12:52:45 +0000706 The `f' argument must have a `readline' method. Optional second
707 argument is the `source' specifying the name of the file being read. If
708 not given, it is taken from f.name. If `f' has no `name' attribute,
709 `<???>' is used.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000710 """
Fred Drakea4923622010-08-09 12:52:45 +0000711 if source is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000712 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000713 source = f.name
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000714 except AttributeError:
Fred Drakea4923622010-08-09 12:52:45 +0000715 source = '<???>'
716 self._read(f, source)
717
718 def read_string(self, string, source='<string>'):
719 """Read configuration from a given string."""
720 sfile = io.StringIO(string)
721 self.read_file(sfile, source)
722
723 def read_dict(self, dictionary, source='<dict>'):
724 """Read configuration from a dictionary.
725
726 Keys are section names, values are dictionaries with keys and values
727 that should be present in the section. If the used dictionary type
728 preserves order, sections and their keys will be added in order.
729
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000730 All types held in the dictionary are converted to strings during
731 reading, including section names, option names and keys.
732
Fred Drakea4923622010-08-09 12:52:45 +0000733 Optional second argument is the `source' specifying the name of the
734 dictionary being read.
735 """
736 elements_added = set()
737 for section, keys in dictionary.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000738 section = str(section)
Fred Drakea4923622010-08-09 12:52:45 +0000739 try:
740 self.add_section(section)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000741 except (DuplicateSectionError, ValueError):
Fred Drakea4923622010-08-09 12:52:45 +0000742 if self._strict and section in elements_added:
743 raise
744 elements_added.add(section)
745 for key, value in keys.items():
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000746 key = self.optionxform(str(key))
Fred Drakecc645b92010-09-04 04:35:34 +0000747 if value is not None:
748 value = str(value)
Fred Drakea4923622010-08-09 12:52:45 +0000749 if self._strict and (section, key) in elements_added:
750 raise DuplicateOptionError(section, key, source)
751 elements_added.add((section, key))
752 self.set(section, key, value)
753
754 def readfp(self, fp, filename=None):
755 """Deprecated, use read_file instead."""
756 warnings.warn(
757 "This method will be removed in future versions. "
758 "Use 'parser.read_file()' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000759 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000760 )
761 self.read_file(fp, source=filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000762
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000763 def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000764 """Get an option value for a given section.
765
766 If `vars' is provided, it must be a dictionary. The option is looked up
767 in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000768 If the key is not found and `fallback' is provided, it is used as
769 a fallback value. `None' can be provided as a `fallback' value.
770
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000771 If interpolation is enabled and the optional argument `raw' is False,
772 all interpolations are expanded in the return values.
773
774 Arguments `raw', `vars', and `fallback' are keyword only.
775
776 The section DEFAULT is special.
Fred Drakecc645b92010-09-04 04:35:34 +0000777 """
778 try:
779 d = self._unify_values(section, vars)
780 except NoSectionError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000781 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000782 raise
Fred Drakefce65572002-10-25 18:08:18 +0000783 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000784 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000785 option = self.optionxform(option)
786 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000787 value = d[option]
Fred Drakecc645b92010-09-04 04:35:34 +0000788 except KeyError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000789 if fallback is _UNSET:
Fred Drakefce65572002-10-25 18:08:18 +0000790 raise NoOptionError(option, section)
Fred Drakecc645b92010-09-04 04:35:34 +0000791 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000792 return fallback
Fred Drake2a37f9f2000-09-27 22:43:54 +0000793
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000794 if raw or value is None:
795 return value
796 else:
797 return self._interpolation.before_get(self, section, option, value,
798 d)
Fred Drake2ca041f2002-09-27 15:49:56 +0000799
Łukasz Langa26d513c2010-11-10 18:57:39 +0000800 def _get(self, section, conv, option, **kwargs):
801 return conv(self.get(section, option, **kwargs))
Guido van Rossum3d209861997-12-09 16:10:31 +0000802
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000803 def getint(self, section, option, *, raw=False, vars=None,
804 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000805 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000806 return self._get(section, int, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000807 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000808 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000809 raise
810 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000811 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000812
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000813 def getfloat(self, section, option, *, raw=False, vars=None,
814 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000815 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000816 return self._get(section, float, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000817 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000818 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000819 raise
820 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000821 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000822
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000823 def getboolean(self, section, option, *, raw=False, vars=None,
824 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000825 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000826 return self._get(section, self._convert_to_boolean, option,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000827 raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000828 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000829 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000830 raise
831 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000832 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000833
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000834 def items(self, section, raw=False, vars=None):
835 """Return a list of (name, value) tuples for each option in a section.
836
837 All % interpolations are expanded in the return values, based on the
838 defaults passed into the constructor, unless the optional argument
839 `raw' is true. Additional substitutions may be provided using the
840 `vars' argument, which must be a dictionary whose contents overrides
841 any pre-existing defaults.
842
843 The section DEFAULT is special.
844 """
845 d = self._defaults.copy()
846 try:
847 d.update(self._sections[section])
848 except KeyError:
849 if section != self.default_section:
850 raise NoSectionError(section)
851 # Update with the entry specific variables
852 if vars:
853 for key, value in vars.items():
854 d[self.optionxform(key)] = value
Łukasz Langa24bcc612010-12-04 11:48:11 +0000855 value_getter = lambda option: self._interpolation.before_get(self,
856 section, option, d[option], d)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000857 if raw:
Łukasz Langa24bcc612010-12-04 11:48:11 +0000858 value_getter = lambda option: d[option]
859 return [(option, value_getter(option)) for option in d.keys()]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000860
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000861 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000862 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000863
Eric S. Raymond417c4892000-07-10 18:11:00 +0000864 def has_option(self, section, option):
865 """Check for the existence of a given option in a given section."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000866 if not section or section == self.default_section:
Fred Drakec2ff9052002-09-27 15:33:11 +0000867 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000868 return option in self._defaults
869 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000870 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000871 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000872 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000873 return (option in self._sections[section]
874 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000875
Fred Drake03c44a32010-02-19 06:08:41 +0000876 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000877 """Set an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000878 if value:
879 value = self._interpolation.before_set(self, section, option,
880 value)
881 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000882 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000883 else:
884 try:
Fred Drakefce65572002-10-25 18:08:18 +0000885 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000886 except KeyError:
887 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000888 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000889
Georg Brandl96a60ae2010-07-28 13:13:46 +0000890 def write(self, fp, space_around_delimiters=True):
891 """Write an .ini-format representation of the configuration state.
892
893 If `space_around_delimiters' is True (the default), delimiters
894 between keys and values are surrounded by spaces.
895 """
896 if space_around_delimiters:
897 d = " {} ".format(self._delimiters[0])
898 else:
899 d = self._delimiters[0]
Fred Drakefce65572002-10-25 18:08:18 +0000900 if self._defaults:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000901 self._write_section(fp, self.default_section,
Łukasz Langac264c092010-11-20 16:15:37 +0000902 self._defaults.items(), d)
Fred Drakefce65572002-10-25 18:08:18 +0000903 for section in self._sections:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000904 self._write_section(fp, section,
905 self._sections[section].items(), d)
906
907 def _write_section(self, fp, section_name, section_items, delimiter):
908 """Write a single section to the specified `fp'."""
909 fp.write("[{}]\n".format(section_name))
910 for key, value in section_items:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000911 value = self._interpolation.before_write(self, section_name, key,
912 value)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000913 if value is not None or not self._allow_no_value:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000914 value = delimiter + str(value).replace('\n', '\n\t')
915 else:
916 value = ""
917 fp.write("{}{}\n".format(key, value))
918 fp.write("\n")
Eric S. Raymond417c4892000-07-10 18:11:00 +0000919
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000920 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000921 """Remove an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000922 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000923 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000924 else:
925 try:
Fred Drakefce65572002-10-25 18:08:18 +0000926 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000927 except KeyError:
928 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000929 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000930 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000931 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000932 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000933 return existed
934
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000935 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000936 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000937 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000938 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000939 del self._sections[section]
Łukasz Langa49afa382010-11-11 19:53:23 +0000940 del self._proxies[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000941 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000942
Łukasz Langa26d513c2010-11-10 18:57:39 +0000943 def __getitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000944 if key != self.default_section and not self.has_section(key):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000945 raise KeyError(key)
Łukasz Langa49afa382010-11-11 19:53:23 +0000946 return self._proxies[key]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000947
948 def __setitem__(self, key, value):
949 # To conform with the mapping protocol, overwrites existing values in
950 # the section.
951
952 # XXX this is not atomic if read_dict fails at any point. Then again,
953 # no update method in configparser is atomic in this implementation.
954 self.remove_section(key)
955 self.read_dict({key: value})
956
957 def __delitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000958 if key == self.default_section:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000959 raise ValueError("Cannot remove the default section.")
960 if not self.has_section(key):
961 raise KeyError(key)
962 self.remove_section(key)
963
964 def __contains__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000965 return key == self.default_section or self.has_section(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000966
967 def __len__(self):
968 return len(self._sections) + 1 # the default section
969
970 def __iter__(self):
971 # XXX does it break when underlying container state changed?
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000972 return itertools.chain((self.default_section,), self._sections.keys())
Łukasz Langa26d513c2010-11-10 18:57:39 +0000973
Fred Drakefce65572002-10-25 18:08:18 +0000974 def _read(self, fp, fpname):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000975 """Parse a sectioned configuration file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000976
Fred Drakea4923622010-08-09 12:52:45 +0000977 Each section in a configuration file contains a header, indicated by
978 a name in square brackets (`[]'), plus key/value options, indicated by
Georg Brandl96a60ae2010-07-28 13:13:46 +0000979 `name' and `value' delimited with a specific substring (`=' or `:' by
980 default).
981
Fred Drakea4923622010-08-09 12:52:45 +0000982 Values can span multiple lines, as long as they are indented deeper
983 than the first line of the value. Depending on the parser's mode, blank
984 lines may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000985
986 Configuration files may include comments, prefixed by specific
Fred Drakea4923622010-08-09 12:52:45 +0000987 characters (`#' and `;' by default). Comments may appear on their own
988 in an otherwise empty line or may be entered in lines holding values or
Georg Brandl96a60ae2010-07-28 13:13:46 +0000989 section names.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000990 """
Fred Drakea4923622010-08-09 12:52:45 +0000991 elements_added = set()
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000992 cursect = None # None, or a dictionary
Fred Drakea4923622010-08-09 12:52:45 +0000993 sectname = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000994 optname = None
995 lineno = 0
Georg Brandl96a60ae2010-07-28 13:13:46 +0000996 indent_level = 0
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000997 e = None # None, or an exception
Georg Brandl96a60ae2010-07-28 13:13:46 +0000998 for lineno, line in enumerate(fp, start=1):
Georg Brandlf206d0e2010-07-29 11:56:20 +0000999 # strip full line comments
Georg Brandl96a60ae2010-07-28 13:13:46 +00001000 comment_start = None
1001 for prefix in self._startonly_comment_prefixes:
1002 if line.strip().startswith(prefix):
1003 comment_start = 0
1004 break
1005 # strip inline comments
1006 for prefix in self._comment_prefixes:
1007 index = line.find(prefix)
1008 if index == 0 or (index > 0 and line[index-1].isspace()):
1009 comment_start = index
1010 break
1011 value = line[:comment_start].strip()
1012 if not value:
Georg Brandlf206d0e2010-07-29 11:56:20 +00001013 if self._empty_lines_in_values:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001014 # add empty line to the value, but only if there was no
1015 # comment on the line
Georg Brandlf206d0e2010-07-29 11:56:20 +00001016 if (comment_start is None and
1017 cursect is not None and
1018 optname and
1019 cursect[optname] is not None):
1020 cursect[optname].append('') # newlines added at join
Georg Brandl96a60ae2010-07-28 13:13:46 +00001021 else:
1022 # empty line marks end of value
1023 indent_level = sys.maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001024 continue
1025 # continuation line?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001026 first_nonspace = self.NONSPACECRE.search(line)
1027 cur_indent_level = first_nonspace.start() if first_nonspace else 0
1028 if (cursect is not None and optname and
1029 cur_indent_level > indent_level):
1030 cursect[optname].append(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001031 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001032 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001033 indent_level = cur_indent_level
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001034 # is it a section header?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001035 mo = self.SECTCRE.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001036 if mo:
1037 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +00001038 if sectname in self._sections:
Fred Drakea4923622010-08-09 12:52:45 +00001039 if self._strict and sectname in elements_added:
1040 raise DuplicateSectionError(sectname, fpname,
1041 lineno)
Fred Drakefce65572002-10-25 18:08:18 +00001042 cursect = self._sections[sectname]
Fred Drakea4923622010-08-09 12:52:45 +00001043 elements_added.add(sectname)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001044 elif sectname == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001045 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001046 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001047 cursect = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +00001048 self._sections[sectname] = cursect
Łukasz Langa49afa382010-11-11 19:53:23 +00001049 self._proxies[sectname] = SectionProxy(self, sectname)
Fred Drakea4923622010-08-09 12:52:45 +00001050 elements_added.add(sectname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001051 # So sections can't start with a continuation line
1052 optname = None
1053 # no section header in the file?
1054 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001055 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001056 # an option line?
1057 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001058 mo = self._optcre.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001059 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +00001060 optname, vi, optval = mo.group('option', 'vi', 'value')
Georg Brandl96a60ae2010-07-28 13:13:46 +00001061 if not optname:
1062 e = self._handle_error(e, fpname, lineno, line)
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001063 optname = self.optionxform(optname.rstrip())
Fred Drakea4923622010-08-09 12:52:45 +00001064 if (self._strict and
1065 (sectname, optname) in elements_added):
1066 raise DuplicateOptionError(sectname, optname,
1067 fpname, lineno)
1068 elements_added.add((sectname, optname))
Fred Drake03c44a32010-02-19 06:08:41 +00001069 # This check is fine because the OPTCRE cannot
1070 # match if it would set optval to None
1071 if optval is not None:
Fred Drake03c44a32010-02-19 06:08:41 +00001072 optval = optval.strip()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001073 # allow empty values
1074 if optval == '""':
1075 optval = ''
1076 cursect[optname] = [optval]
1077 else:
1078 # valueless option handling
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001079 cursect[optname] = None
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001080 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001081 # a non-fatal parsing error occurred. set up the
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001082 # exception but keep going. the exception will be
1083 # raised at the end of the file and will contain a
1084 # list of all bogus lines
Georg Brandl96a60ae2010-07-28 13:13:46 +00001085 e = self._handle_error(e, fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001086 # if any parsing errors occurred, raise an exception
1087 if e:
1088 raise e
Georg Brandl96a60ae2010-07-28 13:13:46 +00001089 self._join_multiline_values()
Fred Drakefce65572002-10-25 18:08:18 +00001090
Georg Brandl96a60ae2010-07-28 13:13:46 +00001091 def _join_multiline_values(self):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001092 defaults = self.default_section, self._defaults
1093 all_sections = itertools.chain((defaults,),
1094 self._sections.items())
1095 for section, options in all_sections:
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001096 for name, val in options.items():
1097 if isinstance(val, list):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001098 val = '\n'.join(val).rstrip()
1099 options[name] = self._interpolation.before_read(self,
1100 section,
1101 name, val)
Fred Drakefce65572002-10-25 18:08:18 +00001102
Georg Brandl96a60ae2010-07-28 13:13:46 +00001103 def _handle_error(self, exc, fpname, lineno, line):
1104 if not exc:
1105 exc = ParsingError(fpname)
1106 exc.append(lineno, repr(line))
1107 return exc
1108
Fred Drakecc645b92010-09-04 04:35:34 +00001109 def _unify_values(self, section, vars):
1110 """Create a copy of the DEFAULTSECT with values from a specific
1111 `section' and the `vars' dictionary. If provided, values in `vars'
1112 take precendence.
Fred Drakefce65572002-10-25 18:08:18 +00001113 """
1114 d = self._defaults.copy()
1115 try:
1116 d.update(self._sections[section])
1117 except KeyError:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001118 if section != self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001119 raise NoSectionError(section)
1120 # Update with the entry specific variables
David Goodger68a1abd2004-10-03 15:40:25 +00001121 if vars:
1122 for key, value in vars.items():
Fred Drakecc645b92010-09-04 04:35:34 +00001123 if value is not None:
1124 value = str(value)
David Goodger68a1abd2004-10-03 15:40:25 +00001125 d[self.optionxform(key)] = value
Fred Drakecc645b92010-09-04 04:35:34 +00001126 return d
1127
1128 def _convert_to_boolean(self, value):
1129 """Return a boolean value translating from other types if necessary.
1130 """
1131 if value.lower() not in self.BOOLEAN_STATES:
1132 raise ValueError('Not a boolean: %s' % value)
1133 return self.BOOLEAN_STATES[value.lower()]
1134
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001135 def _validate_value_types(self, *, section="", option="", value=""):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001136 """Raises a TypeError for non-string values.
1137
1138 The only legal non-string value if we allow valueless
1139 options is None, so we need to check if the value is a
1140 string if:
1141 - we do not allow valueless options, or
1142 - we allow valueless options but the value is not None
1143
1144 For compatibility reasons this method is not used in classic set()
1145 for RawConfigParsers and ConfigParsers. It is invoked in every
1146 case for mapping protocol access and in SafeConfigParser.set().
1147 """
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001148 if not isinstance(section, str):
1149 raise TypeError("section names must be strings")
1150 if not isinstance(option, str):
1151 raise TypeError("option keys must be strings")
Łukasz Langa26d513c2010-11-10 18:57:39 +00001152 if not self._allow_no_value or value:
1153 if not isinstance(value, str):
1154 raise TypeError("option values must be strings")
1155
1156
Fred Drakecc645b92010-09-04 04:35:34 +00001157class ConfigParser(RawConfigParser):
1158 """ConfigParser implementing interpolation."""
1159
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001160 _DEFAULT_INTERPOLATION = BrokenInterpolation()
Fred Drakecc645b92010-09-04 04:35:34 +00001161
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001162 def __init__(self, *args, **kwargs):
1163 super().__init__(*args, **kwargs)
1164 if self.__class__ is ConfigParser:
1165 warnings.warn(
1166 "The ConfigParser class will be removed in future versions."
1167 " Use SafeConfigParser instead.",
1168 DeprecationWarning, stacklevel=2
1169 )
Fred Drakebc12b012004-05-18 02:25:51 +00001170
Fred Drake0eebd5c2002-10-25 21:52:00 +00001171
1172class SafeConfigParser(ConfigParser):
Georg Brandl96a60ae2010-07-28 13:13:46 +00001173 """ConfigParser implementing sane interpolation."""
Fred Drake0eebd5c2002-10-25 21:52:00 +00001174
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001175 _DEFAULT_INTERPOLATION = BasicInterpolation()
David Goodger1cbf2062004-10-03 15:55:09 +00001176
Fred Drake03c44a32010-02-19 06:08:41 +00001177 def set(self, section, option, value=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001178 """Set an option. Extends RawConfigParser.set by validating type and
1179 interpolation syntax on the value."""
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001180 self._validate_value_types(option=option, value=value)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001181 super().set(section, option, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001182
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001183 def add_section(self, section):
1184 """Create a new section in the configuration. Extends
1185 RawConfigParser.add_section by validating if the section name is
1186 a string."""
1187 self._validate_value_types(section=section)
1188 super().add_section(section)
1189
Łukasz Langa26d513c2010-11-10 18:57:39 +00001190
1191class SectionProxy(MutableMapping):
1192 """A proxy for a single section from a parser."""
1193
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001194 def __init__(self, parser, name):
1195 """Creates a view on a section of the specified `name` in `parser`."""
Łukasz Langa26d513c2010-11-10 18:57:39 +00001196 self._parser = parser
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001197 self._name = name
Łukasz Langa26d513c2010-11-10 18:57:39 +00001198
1199 def __repr__(self):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001200 return '<Section: {}>'.format(self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001201
1202 def __getitem__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001203 if not self._parser.has_option(self._name, key):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001204 raise KeyError(key)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001205 return self._parser.get(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001206
1207 def __setitem__(self, key, value):
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001208 self._parser._validate_value_types(option=key, value=value)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001209 return self._parser.set(self._name, key, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001210
1211 def __delitem__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001212 if not self._parser.has_option(self._name, key):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001213 raise KeyError(key)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001214 return self._parser.remove_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001215
1216 def __contains__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001217 return self._parser.has_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001218
1219 def __len__(self):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001220 # XXX weak performance
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001221 return len(self._parser.options(self._name))
Łukasz Langa26d513c2010-11-10 18:57:39 +00001222
1223 def __iter__(self):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001224 # XXX weak performance
1225 # XXX does not break when underlying container state changed
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001226 return self._parser.options(self._name).__iter__()
1227
Łukasz Langa2f0fd0f2010-12-04 17:48:18 +00001228 def get(self, option, fallback=None, *, raw=False, vars=None):
1229 return self._parser.get(self._name, option, raw=raw, vars=vars,
1230 fallback=fallback)
1231
1232 def getint(self, option, fallback=None, *, raw=False, vars=None):
1233 return self._parser.getint(self._name, option, raw=raw, vars=vars,
1234 fallback=fallback)
1235
1236 def getfloat(self, option, fallback=None, *, raw=False, vars=None):
1237 return self._parser.getfloat(self._name, option, raw=raw, vars=vars,
1238 fallback=fallback)
1239
1240 def getboolean(self, option, fallback=None, *, raw=False, vars=None):
1241 return self._parser.getboolean(self._name, option, raw=raw, vars=vars,
1242 fallback=fallback)
1243
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001244 @property
1245 def parser(self):
1246 # The parser object of the proxy is read-only.
1247 return self._parser
1248
1249 @property
1250 def name(self):
1251 # The name of the section on a proxy is read-only.
1252 return self._name