blob: aba444cb33c32eb002d45eb1c479af0ff2b16d6a [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,
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
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000268 Current implementation raises this exception when the source text into
269 which substitutions are made does not conform to the required syntax.
Fred Drakea4923622010-08-09 12:52:45 +0000270 """
Neal Norwitzce1d9442002-12-30 23:38:47 +0000271
Georg Brandl96a60ae2010-07-28 13:13:46 +0000272
Fred Drakee2c64912002-12-31 17:23:27 +0000273class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000274 """Raised when substitutions are nested too deeply."""
275
Fred Drake2a37f9f2000-09-27 22:43:54 +0000276 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000277 msg = ("Value interpolation too deeply recursive:\n"
278 "\tsection: [%s]\n"
279 "\toption : %s\n"
280 "\trawval : %s\n"
281 % (section, option, rawval))
282 InterpolationError.__init__(self, option, section, msg)
Michael Foordbd6c0792010-07-25 23:09:25 +0000283 self.args = (option, section, rawval)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000284
Georg Brandl96a60ae2010-07-28 13:13:46 +0000285
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000286class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000287 """Raised when a configuration file does not follow legal syntax."""
288
Fred Drakea4923622010-08-09 12:52:45 +0000289 def __init__(self, source=None, filename=None):
290 # Exactly one of `source'/`filename' arguments has to be given.
291 # `filename' kept for compatibility.
292 if filename and source:
293 raise ValueError("Cannot specify both `filename' and `source'. "
294 "Use `source'.")
295 elif not filename and not source:
296 raise ValueError("Required argument `source' not given.")
297 elif filename:
298 source = filename
299 Error.__init__(self, 'Source contains parsing errors: %s' % source)
300 self.source = source
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000301 self.errors = []
Fred Drakea4923622010-08-09 12:52:45 +0000302 self.args = (source, )
303
304 @property
305 def filename(self):
306 """Deprecated, use `source'."""
307 warnings.warn(
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000308 "The 'filename' attribute will be removed in future versions. "
Fred Drakea4923622010-08-09 12:52:45 +0000309 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000310 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000311 )
312 return self.source
313
314 @filename.setter
315 def filename(self, value):
316 """Deprecated, user `source'."""
317 warnings.warn(
318 "The 'filename' attribute will be removed in future versions. "
319 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000320 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000321 )
322 self.source = value
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000323
324 def append(self, lineno, line):
325 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000326 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000327
Georg Brandl96a60ae2010-07-28 13:13:46 +0000328
Fred Drake2a37f9f2000-09-27 22:43:54 +0000329class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000330 """Raised when a key-value pair is found before any section header."""
331
Fred Drake2a37f9f2000-09-27 22:43:54 +0000332 def __init__(self, filename, lineno, line):
333 Error.__init__(
334 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000335 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000336 (filename, lineno, line))
Fred Drakea4923622010-08-09 12:52:45 +0000337 self.source = filename
Fred Drake2a37f9f2000-09-27 22:43:54 +0000338 self.lineno = lineno
339 self.line = line
Michael Foordbd6c0792010-07-25 23:09:25 +0000340 self.args = (filename, lineno, line)
Guido van Rossum3d209861997-12-09 16:10:31 +0000341
Georg Brandl96a60ae2010-07-28 13:13:46 +0000342
Fred Drakecc645b92010-09-04 04:35:34 +0000343# Used in parsers to denote selecting a backwards-compatible inline comment
344# character behavior (; and # are comments at the start of a line, but ; only
345# inline)
346_COMPATIBLE = object()
347
348# Used in parser getters to indicate the default behaviour when a specific
349# option is not found it to raise an exception. Created to enable `None' as
350# a valid fallback value.
351_UNSET = object()
352
353
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000354class Interpolation:
355 """Dummy interpolation that passes the value through with no changes."""
356
357 def before_get(self, parser, section, option, value, defaults):
358 return value
359
360 def before_set(self, parser, section, option, value):
361 return value
362
363 def before_read(self, parser, section, option, value):
364 return value
365
366 def before_write(self, parser, section, option, value):
367 return value
368
369
370class BasicInterpolation(Interpolation):
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000371 """Interpolation as implemented in the classic ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000372
373 The option values can contain format strings which refer to other values in
374 the same section, or values in the special default section.
375
376 For example:
377
378 something: %(dir)s/whatever
379
380 would resolve the "%(dir)s" to the value of dir. All reference
381 expansions are done late, on demand. If a user needs to use a bare % in
382 a configuration file, she can escape it by writing %%. Other other % usage
383 is considered a user error and raises `InterpolationSyntaxError'."""
384
385 _KEYCRE = re.compile(r"%\(([^)]+)\)s")
386
387 def before_get(self, parser, section, option, value, defaults):
388 L = []
389 self._interpolate_some(parser, option, L, value, section, defaults, 1)
390 return ''.join(L)
391
392 def before_set(self, parser, section, option, value):
393 tmp_value = value.replace('%%', '') # escaped percent signs
394 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
395 if '%' in tmp_value:
396 raise ValueError("invalid interpolation syntax in %r at "
397 "position %d" % (value, tmp_value.find('%')))
398 return value
399
400 def _interpolate_some(self, parser, option, accum, rest, section, map,
401 depth):
402 if depth > MAX_INTERPOLATION_DEPTH:
403 raise InterpolationDepthError(option, section, rest)
404 while rest:
405 p = rest.find("%")
406 if p < 0:
407 accum.append(rest)
408 return
409 if p > 0:
410 accum.append(rest[:p])
411 rest = rest[p:]
412 # p is no longer used
413 c = rest[1:2]
414 if c == "%":
415 accum.append("%")
416 rest = rest[2:]
417 elif c == "(":
418 m = self._KEYCRE.match(rest)
419 if m is None:
420 raise InterpolationSyntaxError(option, section,
421 "bad interpolation variable reference %r" % rest)
422 var = parser.optionxform(m.group(1))
423 rest = rest[m.end():]
424 try:
425 v = map[var]
426 except KeyError:
427 raise InterpolationMissingOptionError(
428 option, section, rest, var)
429 if "%" in v:
430 self._interpolate_some(parser, option, accum, v,
431 section, map, depth + 1)
432 else:
433 accum.append(v)
434 else:
435 raise InterpolationSyntaxError(
436 option, section,
437 "'%%' must be followed by '%%' or '(', "
438 "found: %r" % (rest,))
439
440
441class ExtendedInterpolation(Interpolation):
442 """Advanced variant of interpolation, supports the syntax used by
443 `zc.buildout'. Enables interpolation between sections."""
444
445 _KEYCRE = re.compile(r"\$\{([^}]+)\}")
446
447 def before_get(self, parser, section, option, value, defaults):
448 L = []
449 self._interpolate_some(parser, option, L, value, section, defaults, 1)
450 return ''.join(L)
451
452 def before_set(self, parser, section, option, value):
453 tmp_value = value.replace('$$', '') # escaped dollar signs
454 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
455 if '$' in tmp_value:
456 raise ValueError("invalid interpolation syntax in %r at "
457 "position %d" % (value, tmp_value.find('%')))
458 return value
459
460 def _interpolate_some(self, parser, option, accum, rest, section, map,
461 depth):
462 if depth > MAX_INTERPOLATION_DEPTH:
463 raise InterpolationDepthError(option, section, rest)
464 while rest:
465 p = rest.find("$")
466 if p < 0:
467 accum.append(rest)
468 return
469 if p > 0:
470 accum.append(rest[:p])
471 rest = rest[p:]
472 # p is no longer used
473 c = rest[1:2]
474 if c == "$":
475 accum.append("$")
476 rest = rest[2:]
477 elif c == "{":
478 m = self._KEYCRE.match(rest)
479 if m is None:
480 raise InterpolationSyntaxError(option, section,
481 "bad interpolation variable reference %r" % rest)
482 path = parser.optionxform(m.group(1)).split(':')
483 rest = rest[m.end():]
484 sect = section
485 opt = option
486 try:
487 if len(path) == 1:
488 opt = path[0]
489 v = map[opt]
490 elif len(path) == 2:
491 sect = path[0]
492 opt = path[1]
493 v = parser.get(sect, opt, raw=True)
494 else:
495 raise InterpolationSyntaxError(
496 option, section,
497 "More than one ':' found: %r" % (rest,))
498 except KeyError:
499 raise InterpolationMissingOptionError(
500 option, section, rest, var)
501 if "$" in v:
502 self._interpolate_some(parser, opt, accum, v, sect,
503 dict(parser.items(sect, raw=True)),
504 depth + 1)
505 else:
506 accum.append(v)
507 else:
508 raise InterpolationSyntaxError(
509 option, section,
510 "'$' must be followed by '$' or '{', "
511 "found: %r" % (rest,))
512
513
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000514class LegacyInterpolation(Interpolation):
515 """Deprecated interpolation used in old versions of ConfigParser.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000516 Use BasicInterpolation or ExtendedInterpolation instead."""
517
518 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
519
520 def before_get(self, parser, section, option, value, vars):
521 rawval = value
522 depth = MAX_INTERPOLATION_DEPTH
523 while depth: # Loop through this until it's done
524 depth -= 1
525 if value and "%(" in value:
526 replace = functools.partial(self._interpolation_replace,
527 parser=parser)
528 value = self._KEYCRE.sub(replace, value)
529 try:
530 value = value % vars
531 except KeyError as e:
532 raise InterpolationMissingOptionError(
533 option, section, rawval, e.args[0])
534 else:
535 break
536 if value and "%(" in value:
537 raise InterpolationDepthError(option, section, rawval)
538 return value
539
540 def before_set(self, parser, section, option, value):
541 return value
542
543 @staticmethod
544 def _interpolation_replace(match, parser):
545 s = match.group(1)
546 if s is None:
547 return match.group()
548 else:
549 return "%%(%s)s" % parser.optionxform(s)
550
551
Łukasz Langa26d513c2010-11-10 18:57:39 +0000552class RawConfigParser(MutableMapping):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000553 """ConfigParser that does not do interpolation."""
554
555 # Regular expressions for parsing section headers and options
556 _SECT_TMPL = r"""
557 \[ # [
558 (?P<header>[^]]+) # very permissive!
559 \] # ]
560 """
561 _OPT_TMPL = r"""
562 (?P<option>.*?) # very permissive!
563 \s*(?P<vi>{delim})\s* # any number of space/tab,
564 # followed by any of the
565 # allowed delimiters,
566 # followed by any space/tab
567 (?P<value>.*)$ # everything up to eol
568 """
569 _OPT_NV_TMPL = r"""
570 (?P<option>.*?) # very permissive!
571 \s*(?: # any number of space/tab,
572 (?P<vi>{delim})\s* # optionally followed by
573 # any of the allowed
574 # delimiters, followed by any
575 # space/tab
576 (?P<value>.*))?$ # everything up to eol
577 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000578 # Interpolation algorithm to be used if the user does not specify another
579 _DEFAULT_INTERPOLATION = Interpolation()
Georg Brandl96a60ae2010-07-28 13:13:46 +0000580 # Compiled regular expression for matching sections
581 SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
582 # Compiled regular expression for matching options with typical separators
583 OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
584 # Compiled regular expression for matching options with optional values
585 # delimited using typical separators
586 OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
587 # Compiled regular expression for matching leading whitespace in a line
588 NONSPACECRE = re.compile(r"\S")
Fred Drakecc645b92010-09-04 04:35:34 +0000589 # Possible boolean values in the configuration.
590 BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
591 '0': False, 'no': False, 'false': False, 'off': False}
Georg Brandl96a60ae2010-07-28 13:13:46 +0000592
Fred Drake03c44a32010-02-19 06:08:41 +0000593 def __init__(self, defaults=None, dict_type=_default_dict,
Fred Drakea4923622010-08-09 12:52:45 +0000594 allow_no_value=False, *, delimiters=('=', ':'),
595 comment_prefixes=_COMPATIBLE, strict=False,
Łukasz Langac264c092010-11-20 16:15:37 +0000596 empty_lines_in_values=True,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000597 default_section=DEFAULTSECT,
598 interpolation=_UNSET):
599
Thomas Wouters89f507f2006-12-13 04:49:30 +0000600 self._dict = dict_type
601 self._sections = self._dict()
602 self._defaults = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000603 self._proxies = self._dict()
Łukasz Langac264c092010-11-20 16:15:37 +0000604 self._proxies[default_section] = SectionProxy(self, default_section)
David Goodger68a1abd2004-10-03 15:40:25 +0000605 if defaults:
606 for key, value in defaults.items():
607 self._defaults[self.optionxform(key)] = value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000608 self._delimiters = tuple(delimiters)
609 if delimiters == ('=', ':'):
610 self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
611 else:
Fred Drakea4923622010-08-09 12:52:45 +0000612 d = "|".join(re.escape(d) for d in delimiters)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000613 if allow_no_value:
Fred Drakea4923622010-08-09 12:52:45 +0000614 self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000615 re.VERBOSE)
616 else:
Fred Drakea4923622010-08-09 12:52:45 +0000617 self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000618 re.VERBOSE)
Fred Drakecc645b92010-09-04 04:35:34 +0000619 if comment_prefixes is _COMPATIBLE:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000620 self._startonly_comment_prefixes = ('#',)
621 self._comment_prefixes = (';',)
622 else:
623 self._startonly_comment_prefixes = ()
624 self._comment_prefixes = tuple(comment_prefixes or ())
Fred Drakea4923622010-08-09 12:52:45 +0000625 self._strict = strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000626 self._allow_no_value = allow_no_value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000627 self._empty_lines_in_values = empty_lines_in_values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000628 if interpolation is _UNSET:
629 self._interpolation = self._DEFAULT_INTERPOLATION
630 else:
631 self._interpolation = interpolation
632 self.default_section=default_section
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
Fred Drakea4923622010-08-09 12:52:45 +0000699 The `f' argument must have a `readline' method. Optional second
700 argument is the `source' specifying the name of the file being read. If
701 not given, it is taken from f.name. If `f' has no `name' attribute,
702 `<???>' 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
737 elements_added.add(section)
738 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 Langab6a6f5f2010-12-03 16:28:00 +0000827 def items(self, section, raw=False, vars=None):
828 """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 """
838 d = self._defaults.copy()
839 try:
840 d.update(self._sections[section])
841 except KeyError:
842 if section != self.default_section:
843 raise NoSectionError(section)
844 # Update with the entry specific variables
845 if vars:
846 for key, value in vars.items():
847 d[self.optionxform(key)] = value
Łukasz Langa24bcc612010-12-04 11:48:11 +0000848 value_getter = lambda option: self._interpolation.before_get(self,
849 section, option, d[option], d)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000850 if raw:
Łukasz Langa24bcc612010-12-04 11:48:11 +0000851 value_getter = lambda option: d[option]
852 return [(option, value_getter(option)) for option in d.keys()]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000853
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000854 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000855 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000856
Eric S. Raymond417c4892000-07-10 18:11:00 +0000857 def has_option(self, section, option):
858 """Check for the existence of a given option in a given section."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000859 if not section or section == self.default_section:
Fred Drakec2ff9052002-09-27 15:33:11 +0000860 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000861 return option in self._defaults
862 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000863 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000864 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000865 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000866 return (option in self._sections[section]
867 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000868
Fred Drake03c44a32010-02-19 06:08:41 +0000869 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000870 """Set an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000871 if value:
872 value = self._interpolation.before_set(self, section, option,
873 value)
874 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000875 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000876 else:
877 try:
Fred Drakefce65572002-10-25 18:08:18 +0000878 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000879 except KeyError:
880 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000881 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000882
Georg Brandl96a60ae2010-07-28 13:13:46 +0000883 def write(self, fp, space_around_delimiters=True):
884 """Write an .ini-format representation of the configuration state.
885
886 If `space_around_delimiters' is True (the default), delimiters
887 between keys and values are surrounded by spaces.
888 """
889 if space_around_delimiters:
890 d = " {} ".format(self._delimiters[0])
891 else:
892 d = self._delimiters[0]
Fred Drakefce65572002-10-25 18:08:18 +0000893 if self._defaults:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000894 self._write_section(fp, self.default_section,
Łukasz Langac264c092010-11-20 16:15:37 +0000895 self._defaults.items(), d)
Fred Drakefce65572002-10-25 18:08:18 +0000896 for section in self._sections:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000897 self._write_section(fp, section,
898 self._sections[section].items(), d)
899
900 def _write_section(self, fp, section_name, section_items, delimiter):
901 """Write a single section to the specified `fp'."""
902 fp.write("[{}]\n".format(section_name))
903 for key, value in section_items:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000904 value = self._interpolation.before_write(self, section_name, key,
905 value)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000906 if value is not None or not self._allow_no_value:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000907 value = delimiter + str(value).replace('\n', '\n\t')
908 else:
909 value = ""
910 fp.write("{}{}\n".format(key, value))
911 fp.write("\n")
Eric S. Raymond417c4892000-07-10 18:11:00 +0000912
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000913 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000914 """Remove an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000915 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000916 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000917 else:
918 try:
Fred Drakefce65572002-10-25 18:08:18 +0000919 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000920 except KeyError:
921 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000922 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000923 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000924 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000925 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000926 return existed
927
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000928 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000929 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000930 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000931 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000932 del self._sections[section]
Łukasz Langa49afa382010-11-11 19:53:23 +0000933 del self._proxies[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000934 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000935
Łukasz Langa26d513c2010-11-10 18:57:39 +0000936 def __getitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000937 if key != self.default_section and not self.has_section(key):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000938 raise KeyError(key)
Łukasz Langa49afa382010-11-11 19:53:23 +0000939 return self._proxies[key]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000940
941 def __setitem__(self, key, value):
942 # To conform with the mapping protocol, overwrites existing values in
943 # the section.
944
945 # XXX this is not atomic if read_dict fails at any point. Then again,
946 # no update method in configparser is atomic in this implementation.
947 self.remove_section(key)
948 self.read_dict({key: value})
949
950 def __delitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000951 if key == self.default_section:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000952 raise ValueError("Cannot remove the default section.")
953 if not self.has_section(key):
954 raise KeyError(key)
955 self.remove_section(key)
956
957 def __contains__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000958 return key == self.default_section or self.has_section(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000959
960 def __len__(self):
961 return len(self._sections) + 1 # the default section
962
963 def __iter__(self):
964 # XXX does it break when underlying container state changed?
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000965 return itertools.chain((self.default_section,), self._sections.keys())
Łukasz Langa26d513c2010-11-10 18:57:39 +0000966
Fred Drakefce65572002-10-25 18:08:18 +0000967 def _read(self, fp, fpname):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000968 """Parse a sectioned configuration file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000969
Fred Drakea4923622010-08-09 12:52:45 +0000970 Each section in a configuration file contains a header, indicated by
971 a name in square brackets (`[]'), plus key/value options, indicated by
Georg Brandl96a60ae2010-07-28 13:13:46 +0000972 `name' and `value' delimited with a specific substring (`=' or `:' by
973 default).
974
Fred Drakea4923622010-08-09 12:52:45 +0000975 Values can span multiple lines, as long as they are indented deeper
976 than the first line of the value. Depending on the parser's mode, blank
977 lines may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000978
979 Configuration files may include comments, prefixed by specific
Fred Drakea4923622010-08-09 12:52:45 +0000980 characters (`#' and `;' by default). Comments may appear on their own
981 in an otherwise empty line or may be entered in lines holding values or
Georg Brandl96a60ae2010-07-28 13:13:46 +0000982 section names.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000983 """
Fred Drakea4923622010-08-09 12:52:45 +0000984 elements_added = set()
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000985 cursect = None # None, or a dictionary
Fred Drakea4923622010-08-09 12:52:45 +0000986 sectname = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000987 optname = None
988 lineno = 0
Georg Brandl96a60ae2010-07-28 13:13:46 +0000989 indent_level = 0
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000990 e = None # None, or an exception
Georg Brandl96a60ae2010-07-28 13:13:46 +0000991 for lineno, line in enumerate(fp, start=1):
Georg Brandlf206d0e2010-07-29 11:56:20 +0000992 # strip full line comments
Georg Brandl96a60ae2010-07-28 13:13:46 +0000993 comment_start = None
994 for prefix in self._startonly_comment_prefixes:
995 if line.strip().startswith(prefix):
996 comment_start = 0
997 break
998 # strip inline comments
999 for prefix in self._comment_prefixes:
1000 index = line.find(prefix)
1001 if index == 0 or (index > 0 and line[index-1].isspace()):
1002 comment_start = index
1003 break
1004 value = line[:comment_start].strip()
1005 if not value:
Georg Brandlf206d0e2010-07-29 11:56:20 +00001006 if self._empty_lines_in_values:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001007 # add empty line to the value, but only if there was no
1008 # comment on the line
Georg Brandlf206d0e2010-07-29 11:56:20 +00001009 if (comment_start is None and
1010 cursect is not None and
1011 optname and
1012 cursect[optname] is not None):
1013 cursect[optname].append('') # newlines added at join
Georg Brandl96a60ae2010-07-28 13:13:46 +00001014 else:
1015 # empty line marks end of value
1016 indent_level = sys.maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001017 continue
1018 # continuation line?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001019 first_nonspace = self.NONSPACECRE.search(line)
1020 cur_indent_level = first_nonspace.start() if first_nonspace else 0
1021 if (cursect is not None and optname and
1022 cur_indent_level > indent_level):
1023 cursect[optname].append(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001024 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001025 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001026 indent_level = cur_indent_level
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001027 # is it a section header?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001028 mo = self.SECTCRE.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001029 if mo:
1030 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +00001031 if sectname in self._sections:
Fred Drakea4923622010-08-09 12:52:45 +00001032 if self._strict and sectname in elements_added:
1033 raise DuplicateSectionError(sectname, fpname,
1034 lineno)
Fred Drakefce65572002-10-25 18:08:18 +00001035 cursect = self._sections[sectname]
Fred Drakea4923622010-08-09 12:52:45 +00001036 elements_added.add(sectname)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001037 elif sectname == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001038 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001039 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001040 cursect = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +00001041 self._sections[sectname] = cursect
Łukasz Langa49afa382010-11-11 19:53:23 +00001042 self._proxies[sectname] = SectionProxy(self, sectname)
Fred Drakea4923622010-08-09 12:52:45 +00001043 elements_added.add(sectname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001044 # So sections can't start with a continuation line
1045 optname = None
1046 # no section header in the file?
1047 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001048 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001049 # an option line?
1050 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001051 mo = self._optcre.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001052 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +00001053 optname, vi, optval = mo.group('option', 'vi', 'value')
Georg Brandl96a60ae2010-07-28 13:13:46 +00001054 if not optname:
1055 e = self._handle_error(e, fpname, lineno, line)
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001056 optname = self.optionxform(optname.rstrip())
Fred Drakea4923622010-08-09 12:52:45 +00001057 if (self._strict and
1058 (sectname, optname) in elements_added):
1059 raise DuplicateOptionError(sectname, optname,
1060 fpname, lineno)
1061 elements_added.add((sectname, optname))
Fred Drake03c44a32010-02-19 06:08:41 +00001062 # This check is fine because the OPTCRE cannot
1063 # match if it would set optval to None
1064 if optval is not None:
Fred Drake03c44a32010-02-19 06:08:41 +00001065 optval = optval.strip()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001066 # allow empty values
1067 if optval == '""':
1068 optval = ''
1069 cursect[optname] = [optval]
1070 else:
1071 # valueless option handling
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001072 cursect[optname] = None
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001073 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001074 # a non-fatal parsing error occurred. set up the
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001075 # exception but keep going. the exception will be
1076 # raised at the end of the file and will contain a
1077 # list of all bogus lines
Georg Brandl96a60ae2010-07-28 13:13:46 +00001078 e = self._handle_error(e, fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001079 # if any parsing errors occurred, raise an exception
1080 if e:
1081 raise e
Georg Brandl96a60ae2010-07-28 13:13:46 +00001082 self._join_multiline_values()
Fred Drakefce65572002-10-25 18:08:18 +00001083
Georg Brandl96a60ae2010-07-28 13:13:46 +00001084 def _join_multiline_values(self):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001085 defaults = self.default_section, self._defaults
1086 all_sections = itertools.chain((defaults,),
1087 self._sections.items())
1088 for section, options in all_sections:
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001089 for name, val in options.items():
1090 if isinstance(val, list):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001091 val = '\n'.join(val).rstrip()
1092 options[name] = self._interpolation.before_read(self,
1093 section,
1094 name, val)
Fred Drakefce65572002-10-25 18:08:18 +00001095
Georg Brandl96a60ae2010-07-28 13:13:46 +00001096 def _handle_error(self, exc, fpname, lineno, line):
1097 if not exc:
1098 exc = ParsingError(fpname)
1099 exc.append(lineno, repr(line))
1100 return exc
1101
Fred Drakecc645b92010-09-04 04:35:34 +00001102 def _unify_values(self, section, vars):
1103 """Create a copy of the DEFAULTSECT with values from a specific
1104 `section' and the `vars' dictionary. If provided, values in `vars'
1105 take precendence.
Fred Drakefce65572002-10-25 18:08:18 +00001106 """
1107 d = self._defaults.copy()
1108 try:
1109 d.update(self._sections[section])
1110 except KeyError:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001111 if section != self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001112 raise NoSectionError(section)
1113 # Update with the entry specific variables
David Goodger68a1abd2004-10-03 15:40:25 +00001114 if vars:
1115 for key, value in vars.items():
Fred Drakecc645b92010-09-04 04:35:34 +00001116 if value is not None:
1117 value = str(value)
David Goodger68a1abd2004-10-03 15:40:25 +00001118 d[self.optionxform(key)] = value
Fred Drakecc645b92010-09-04 04:35:34 +00001119 return d
1120
1121 def _convert_to_boolean(self, value):
1122 """Return a boolean value translating from other types if necessary.
1123 """
1124 if value.lower() not in self.BOOLEAN_STATES:
1125 raise ValueError('Not a boolean: %s' % value)
1126 return self.BOOLEAN_STATES[value.lower()]
1127
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001128 def _validate_value_types(self, *, section="", option="", value=""):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001129 """Raises a TypeError for non-string values.
1130
1131 The only legal non-string value if we allow valueless
1132 options is None, so we need to check if the value is a
1133 string if:
1134 - we do not allow valueless options, or
1135 - we allow valueless options but the value is not None
1136
1137 For compatibility reasons this method is not used in classic set()
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001138 for RawConfigParsers. It is invoked in every case for mapping protocol
1139 access and in ConfigParser.set().
Łukasz Langa26d513c2010-11-10 18:57:39 +00001140 """
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001141 if not isinstance(section, str):
1142 raise TypeError("section names must be strings")
1143 if not isinstance(option, str):
1144 raise TypeError("option keys must be strings")
Łukasz Langa26d513c2010-11-10 18:57:39 +00001145 if not self._allow_no_value or value:
1146 if not isinstance(value, str):
1147 raise TypeError("option values must be strings")
1148
1149
Fred Drakecc645b92010-09-04 04:35:34 +00001150class ConfigParser(RawConfigParser):
1151 """ConfigParser implementing interpolation."""
1152
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001153 _DEFAULT_INTERPOLATION = BasicInterpolation()
David Goodger1cbf2062004-10-03 15:55:09 +00001154
Fred Drake03c44a32010-02-19 06:08:41 +00001155 def set(self, section, option, value=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001156 """Set an option. Extends RawConfigParser.set by validating type and
1157 interpolation syntax on the value."""
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001158 self._validate_value_types(option=option, value=value)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001159 super().set(section, option, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001160
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001161 def add_section(self, section):
1162 """Create a new section in the configuration. Extends
1163 RawConfigParser.add_section by validating if the section name is
1164 a string."""
1165 self._validate_value_types(section=section)
1166 super().add_section(section)
1167
Łukasz Langa26d513c2010-11-10 18:57:39 +00001168
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001169class SafeConfigParser(ConfigParser):
1170 """ConfigParser alias for backwards compatibility purposes."""
1171
1172 def __init__(self, *args, **kwargs):
1173 super().__init__(*args, **kwargs)
1174 warnings.warn(
1175 "The SafeConfigParser class has been renamed to ConfigParser "
1176 "in Python 3.2. This alias will be removed in future versions."
1177 " Use ConfigParser directly instead.",
1178 DeprecationWarning, stacklevel=2
1179 )
1180
1181
Łukasz Langa26d513c2010-11-10 18:57:39 +00001182class SectionProxy(MutableMapping):
1183 """A proxy for a single section from a parser."""
1184
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001185 def __init__(self, parser, name):
1186 """Creates a view on a section of the specified `name` in `parser`."""
Łukasz Langa26d513c2010-11-10 18:57:39 +00001187 self._parser = parser
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001188 self._name = name
Łukasz Langa26d513c2010-11-10 18:57:39 +00001189
1190 def __repr__(self):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001191 return '<Section: {}>'.format(self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001192
1193 def __getitem__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001194 if not self._parser.has_option(self._name, key):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001195 raise KeyError(key)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001196 return self._parser.get(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001197
1198 def __setitem__(self, key, value):
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001199 self._parser._validate_value_types(option=key, value=value)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001200 return self._parser.set(self._name, key, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001201
1202 def __delitem__(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.remove_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001206
1207 def __contains__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001208 return self._parser.has_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001209
1210 def __len__(self):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001211 # XXX weak performance
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001212 return len(self._parser.options(self._name))
Łukasz Langa26d513c2010-11-10 18:57:39 +00001213
1214 def __iter__(self):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001215 # XXX weak performance
1216 # XXX does not break when underlying container state changed
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001217 return self._parser.options(self._name).__iter__()
1218
Łukasz Langa2f0fd0f2010-12-04 17:48:18 +00001219 def get(self, option, fallback=None, *, raw=False, vars=None):
1220 return self._parser.get(self._name, option, raw=raw, vars=vars,
1221 fallback=fallback)
1222
1223 def getint(self, option, fallback=None, *, raw=False, vars=None):
1224 return self._parser.getint(self._name, option, raw=raw, vars=vars,
1225 fallback=fallback)
1226
1227 def getfloat(self, option, fallback=None, *, raw=False, vars=None):
1228 return self._parser.getfloat(self._name, option, raw=raw, vars=vars,
1229 fallback=fallback)
1230
1231 def getboolean(self, option, fallback=None, *, raw=False, vars=None):
1232 return self._parser.getboolean(self._name, option, raw=raw, vars=vars,
1233 fallback=fallback)
1234
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001235 @property
1236 def parser(self):
1237 # The parser object of the proxy is read-only.
1238 return self._parser
1239
1240 @property
1241 def name(self):
1242 # The name of the section on a proxy is read-only.
1243 return self._name