Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 1 | """Configuration file parser. |
| 2 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 3 | A configuration file consists of sections, lead by a "[section]" header, |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 4 | and followed by "name: value" entries, with continuations and such in |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 5 | the style of RFC 822. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 6 | |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 7 | The option values can contain format strings which refer to other values in |
| 8 | the same section, or values in a special [DEFAULT] section. |
| 9 | |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 10 | For example: |
| 11 | |
| 12 | something: %(dir)s/whatever |
| 13 | |
| 14 | would resolve the "%(dir)s" to the value of dir. All reference |
| 15 | expansions are done late, on demand. |
| 16 | |
| 17 | Intrinsic defaults can be specified by passing them into the |
| 18 | ConfigParser constructor as a dictionary. |
| 19 | |
| 20 | class: |
| 21 | |
Walter Dörwald | f0dfc7a | 2003-10-20 14:01:56 +0000 | [diff] [blame] | 22 | ConfigParser -- responsible for parsing a list of |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 23 | configuration files, and managing the parsed database. |
| 24 | |
| 25 | methods: |
| 26 | |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 27 | __init__(defaults=None, dict_type=_default_dict, allow_no_value=False, |
| 28 | delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, |
| 29 | strict=False, empty_lines_in_values=True): |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 30 | Create the parser. When `defaults' is given, it is initialized into the |
| 31 | dictionary or intrinsic defaults. The keys must be strings, the values |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 32 | must be appropriate for %()s string interpolation. Note that `__name__' |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 33 | is always an intrinsic default; its value is the section's name. |
| 34 | |
| 35 | When `dict_type' is given, it will be used to create the dictionary |
| 36 | objects for the list of sections, for the options within a section, and |
| 37 | for the default values. |
| 38 | |
| 39 | When `delimiters' is given, it will be used as the set of substrings |
| 40 | that divide keys from values. |
| 41 | |
| 42 | When `comment_prefixes' is given, it will be used as the set of |
| 43 | substrings that prefix comments in a line. |
| 44 | |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 45 | When `strict` is True, the parser won't allow for any section or option |
| 46 | duplicates while reading from a single source (file, string or |
| 47 | dictionary). Default is False. |
| 48 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 49 | When `empty_lines_in_values' is False (default: True), each empty line |
| 50 | marks the end of an option. Otherwise, internal empty lines of |
| 51 | a multiline option are kept as part of the value. |
| 52 | |
| 53 | When `allow_no_value' is True (default: False), options without |
| 54 | values are accepted; the value presented for these is None. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 55 | |
Barry Warsaw | f09f6a5 | 1999-01-26 22:01:37 +0000 | [diff] [blame] | 56 | sections() |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 57 | Return all the configuration section names, sans DEFAULT. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 58 | |
Guido van Rossum | a5a24b7 | 1999-10-04 19:58:22 +0000 | [diff] [blame] | 59 | has_section(section) |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 60 | Return whether the given section exists. |
Guido van Rossum | a5a24b7 | 1999-10-04 19:58:22 +0000 | [diff] [blame] | 61 | |
Eric S. Raymond | 649685a | 2000-07-14 14:28:22 +0000 | [diff] [blame] | 62 | has_option(section, option) |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 63 | Return whether the given option exists in the given section. |
Eric S. Raymond | 649685a | 2000-07-14 14:28:22 +0000 | [diff] [blame] | 64 | |
Barry Warsaw | f09f6a5 | 1999-01-26 22:01:37 +0000 | [diff] [blame] | 65 | options(section) |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 66 | Return list of configuration options for the named section. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 67 | |
Georg Brandl | 8dcaa73 | 2010-07-29 12:17:40 +0000 | [diff] [blame] | 68 | read(filenames, encoding=None) |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 69 | Read and parse the list of named configuration files, given by |
Guido van Rossum | 6a8d84b | 1999-10-04 18:57:27 +0000 | [diff] [blame] | 70 | name. A single filename is also allowed. Non-existing files |
Fred Drake | 8290314 | 2004-05-18 04:24:02 +0000 | [diff] [blame] | 71 | are ignored. Return list of successfully read files. |
Guido van Rossum | 6a8d84b | 1999-10-04 18:57:27 +0000 | [diff] [blame] | 72 | |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 73 | read_file(f, filename=None) |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 74 | Read and parse one configuration file, given as a file object. |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 75 | The filename defaults to f.name; it is only used in error |
| 76 | messages (if f has no `name' attribute, the string `<???>' is used). |
| 77 | |
| 78 | read_string(string) |
| 79 | Read configuration from a given string. |
| 80 | |
| 81 | read_dict(dictionary) |
| 82 | Read configuration from a dictionary. Keys are section names, |
| 83 | values are dictionaries with keys and values that should be present |
| 84 | in the section. If the used dictionary type preserves order, sections |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 85 | and their keys will be added in order. Values are automatically |
| 86 | converted to strings. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 87 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 88 | get(section, option, raw=False, vars=None, fallback=_UNSET) |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 89 | Return a string value for the named option. All % interpolations are |
Barry Warsaw | f09f6a5 | 1999-01-26 22:01:37 +0000 | [diff] [blame] | 90 | expanded in the return values, based on the defaults passed into the |
| 91 | constructor and the DEFAULT section. Additional substitutions may be |
| 92 | provided using the `vars' argument, which must be a dictionary whose |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 93 | contents override any pre-existing defaults. If `option' is a key in |
| 94 | `vars', the value from `vars' is used. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 95 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 96 | getint(section, options, raw=False, vars=None, fallback=_UNSET) |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 97 | Like get(), but convert value to an integer. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 98 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 99 | getfloat(section, options, raw=False, vars=None, fallback=_UNSET) |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 100 | Like get(), but convert value to a float. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 101 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 102 | getboolean(section, options, raw=False, vars=None, fallback=_UNSET) |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 103 | Like get(), but convert value to a boolean (currently case |
Neal Norwitz | f680cc4 | 2002-12-17 01:56:47 +0000 | [diff] [blame] | 104 | insensitively defined as 0, false, no, off for False, and 1, true, |
| 105 | yes, on for True). Returns False or True. |
Eric S. Raymond | 649685a | 2000-07-14 14:28:22 +0000 | [diff] [blame] | 106 | |
Neal Norwitz | f680cc4 | 2002-12-17 01:56:47 +0000 | [diff] [blame] | 107 | items(section, raw=False, vars=None) |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 108 | Return a list of tuples with (name, value) for each option |
Fred Drake | 2ca041f | 2002-09-27 15:49:56 +0000 | [diff] [blame] | 109 | in the section. |
| 110 | |
Eric S. Raymond | 649685a | 2000-07-14 14:28:22 +0000 | [diff] [blame] | 111 | remove_section(section) |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 112 | Remove the given file section and all its options. |
Eric S. Raymond | 649685a | 2000-07-14 14:28:22 +0000 | [diff] [blame] | 113 | |
| 114 | remove_option(section, option) |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 115 | Remove the given option from the given section. |
Eric S. Raymond | 649685a | 2000-07-14 14:28:22 +0000 | [diff] [blame] | 116 | |
| 117 | set(section, option, value) |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 118 | Set the given option. |
Eric S. Raymond | 649685a | 2000-07-14 14:28:22 +0000 | [diff] [blame] | 119 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 120 | write(fp, space_around_delimiters=True) |
| 121 | Write the configuration state in .ini format. If |
| 122 | `space_around_delimiters' is True (the default), delimiters |
| 123 | between keys and values are surrounded by spaces. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 124 | """ |
| 125 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 126 | from collections import MutableMapping, OrderedDict as _default_dict |
| 127 | import functools |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 128 | import io |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 129 | import itertools |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 130 | import re |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 131 | import sys |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 132 | import warnings |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 133 | |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 134 | __all__ = ["NoSectionError", "DuplicateOptionError", "DuplicateSectionError", |
| 135 | "NoOptionError", "InterpolationError", "InterpolationDepthError", |
Fred Drake | 8d5dd98 | 2002-12-30 23:51:45 +0000 | [diff] [blame] | 136 | "InterpolationSyntaxError", "ParsingError", |
David Goodger | 1cbf206 | 2004-10-03 15:55:09 +0000 | [diff] [blame] | 137 | "MissingSectionHeaderError", |
| 138 | "ConfigParser", "SafeConfigParser", "RawConfigParser", |
Fred Drake | c2ff905 | 2002-09-27 15:33:11 +0000 | [diff] [blame] | 139 | "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"] |
Skip Montanaro | e99d5ea | 2001-01-20 19:54:20 +0000 | [diff] [blame] | 140 | |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 141 | DEFAULTSECT = "DEFAULT" |
| 142 | |
Fred Drake | 2a37f9f | 2000-09-27 22:43:54 +0000 | [diff] [blame] | 143 | MAX_INTERPOLATION_DEPTH = 10 |
| 144 | |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 145 | |
Tim Peters | 88869f9 | 2001-01-14 23:36:06 +0000 | [diff] [blame] | 146 | |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 147 | # exception classes |
Fred Drake | 7c1e5ad | 2000-12-11 18:13:19 +0000 | [diff] [blame] | 148 | class Error(Exception): |
Fred Drake | 8d5dd98 | 2002-12-30 23:51:45 +0000 | [diff] [blame] | 149 | """Base class for ConfigParser exceptions.""" |
| 150 | |
Guido van Rossum | 360e4b8 | 2007-05-14 22:51:27 +0000 | [diff] [blame] | 151 | def _get_message(self): |
| 152 | """Getter for 'message'; needed only to override deprecation in |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 153 | BaseException. |
| 154 | """ |
Guido van Rossum | 360e4b8 | 2007-05-14 22:51:27 +0000 | [diff] [blame] | 155 | return self.__message |
| 156 | |
| 157 | def _set_message(self, value): |
| 158 | """Setter for 'message'; needed only to override deprecation in |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 159 | BaseException. |
| 160 | """ |
Guido van Rossum | 360e4b8 | 2007-05-14 22:51:27 +0000 | [diff] [blame] | 161 | self.__message = value |
| 162 | |
| 163 | # BaseException.message has been deprecated since Python 2.6. To prevent |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 164 | # DeprecationWarning from popping up over this pre-existing attribute, use |
| 165 | # a new property that takes lookup precedence. |
Guido van Rossum | 360e4b8 | 2007-05-14 22:51:27 +0000 | [diff] [blame] | 166 | message = property(_get_message, _set_message) |
| 167 | |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 168 | def __init__(self, msg=''): |
Fred Drake | e2c6491 | 2002-12-31 17:23:27 +0000 | [diff] [blame] | 169 | self.message = msg |
Fred Drake | 7c1e5ad | 2000-12-11 18:13:19 +0000 | [diff] [blame] | 170 | Exception.__init__(self, msg) |
Fred Drake | 8d5dd98 | 2002-12-30 23:51:45 +0000 | [diff] [blame] | 171 | |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 172 | def __repr__(self): |
Fred Drake | e2c6491 | 2002-12-31 17:23:27 +0000 | [diff] [blame] | 173 | return self.message |
Fred Drake | 8d5dd98 | 2002-12-30 23:51:45 +0000 | [diff] [blame] | 174 | |
Fred Drake | 7c1e5ad | 2000-12-11 18:13:19 +0000 | [diff] [blame] | 175 | __str__ = __repr__ |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 176 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 177 | |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 178 | class NoSectionError(Error): |
Fred Drake | 8d5dd98 | 2002-12-30 23:51:45 +0000 | [diff] [blame] | 179 | """Raised when no section matches a requested option.""" |
| 180 | |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 181 | def __init__(self, section): |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 182 | Error.__init__(self, 'No section: %r' % (section,)) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 183 | self.section = section |
Michael Foord | bd6c079 | 2010-07-25 23:09:25 +0000 | [diff] [blame] | 184 | self.args = (section, ) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 185 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 186 | |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 187 | class DuplicateSectionError(Error): |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 188 | """Raised when a section is repeated in an input source. |
Fred Drake | 8d5dd98 | 2002-12-30 23:51:45 +0000 | [diff] [blame] | 189 | |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 190 | Possible repetitions that raise this exception are: multiple creation |
| 191 | using the API or in strict parsers when a section is found more than once |
| 192 | in a single input file, string or dictionary. |
| 193 | """ |
| 194 | |
| 195 | def __init__(self, section, source=None, lineno=None): |
| 196 | msg = [repr(section), " already exists"] |
| 197 | if source is not None: |
| 198 | message = ["While reading from ", source] |
| 199 | if lineno is not None: |
| 200 | message.append(" [line {0:2d}]".format(lineno)) |
| 201 | message.append(": section ") |
| 202 | message.extend(msg) |
| 203 | msg = message |
| 204 | else: |
| 205 | msg.insert(0, "Section ") |
| 206 | Error.__init__(self, "".join(msg)) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 207 | self.section = section |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 208 | self.source = source |
| 209 | self.lineno = lineno |
| 210 | self.args = (section, source, lineno) |
| 211 | |
| 212 | |
| 213 | class DuplicateOptionError(Error): |
| 214 | """Raised by strict parsers when an option is repeated in an input source. |
| 215 | |
| 216 | Current implementation raises this exception only when an option is found |
| 217 | more than once in a single file, string or dictionary. |
| 218 | """ |
| 219 | |
| 220 | def __init__(self, section, option, source=None, lineno=None): |
| 221 | msg = [repr(option), " in section ", repr(section), |
| 222 | " already exists"] |
| 223 | if source is not None: |
| 224 | message = ["While reading from ", source] |
| 225 | if lineno is not None: |
| 226 | message.append(" [line {0:2d}]".format(lineno)) |
| 227 | message.append(": option ") |
| 228 | message.extend(msg) |
| 229 | msg = message |
| 230 | else: |
| 231 | msg.insert(0, "Option ") |
| 232 | Error.__init__(self, "".join(msg)) |
| 233 | self.section = section |
| 234 | self.option = option |
| 235 | self.source = source |
| 236 | self.lineno = lineno |
| 237 | self.args = (section, option, source, lineno) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 238 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 239 | |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 240 | class NoOptionError(Error): |
Fred Drake | 8d5dd98 | 2002-12-30 23:51:45 +0000 | [diff] [blame] | 241 | """A requested option was not found.""" |
| 242 | |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 243 | def __init__(self, option, section): |
Fred Drake | e2c6491 | 2002-12-31 17:23:27 +0000 | [diff] [blame] | 244 | Error.__init__(self, "No option %r in section: %r" % |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 245 | (option, section)) |
| 246 | self.option = option |
| 247 | self.section = section |
Michael Foord | bd6c079 | 2010-07-25 23:09:25 +0000 | [diff] [blame] | 248 | self.args = (option, section) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 249 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 250 | |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 251 | class InterpolationError(Error): |
Fred Drake | e2c6491 | 2002-12-31 17:23:27 +0000 | [diff] [blame] | 252 | """Base class for interpolation-related exceptions.""" |
Fred Drake | 8d5dd98 | 2002-12-30 23:51:45 +0000 | [diff] [blame] | 253 | |
Fred Drake | e2c6491 | 2002-12-31 17:23:27 +0000 | [diff] [blame] | 254 | def __init__(self, option, section, msg): |
| 255 | Error.__init__(self, msg) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 256 | self.option = option |
| 257 | self.section = section |
Michael Foord | bd6c079 | 2010-07-25 23:09:25 +0000 | [diff] [blame] | 258 | self.args = (option, section, msg) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 259 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 260 | |
Fred Drake | e2c6491 | 2002-12-31 17:23:27 +0000 | [diff] [blame] | 261 | class InterpolationMissingOptionError(InterpolationError): |
| 262 | """A string substitution required a setting which was not available.""" |
| 263 | |
| 264 | def __init__(self, option, section, rawval, reference): |
| 265 | msg = ("Bad value substitution:\n" |
| 266 | "\tsection: [%s]\n" |
| 267 | "\toption : %s\n" |
| 268 | "\tkey : %s\n" |
| 269 | "\trawval : %s\n" |
| 270 | % (section, option, reference, rawval)) |
| 271 | InterpolationError.__init__(self, option, section, msg) |
| 272 | self.reference = reference |
Michael Foord | bd6c079 | 2010-07-25 23:09:25 +0000 | [diff] [blame] | 273 | self.args = (option, section, rawval, reference) |
Fred Drake | e2c6491 | 2002-12-31 17:23:27 +0000 | [diff] [blame] | 274 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 275 | |
Fred Drake | e2c6491 | 2002-12-31 17:23:27 +0000 | [diff] [blame] | 276 | class InterpolationSyntaxError(InterpolationError): |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 277 | """Raised when the source text contains invalid syntax. |
| 278 | |
| 279 | Current implementation raises this exception only for SafeConfigParser |
| 280 | instances when the source text into which substitutions are made |
| 281 | does not conform to the required syntax. |
| 282 | """ |
Neal Norwitz | ce1d944 | 2002-12-30 23:38:47 +0000 | [diff] [blame] | 283 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 284 | |
Fred Drake | e2c6491 | 2002-12-31 17:23:27 +0000 | [diff] [blame] | 285 | class InterpolationDepthError(InterpolationError): |
Fred Drake | 8d5dd98 | 2002-12-30 23:51:45 +0000 | [diff] [blame] | 286 | """Raised when substitutions are nested too deeply.""" |
| 287 | |
Fred Drake | 2a37f9f | 2000-09-27 22:43:54 +0000 | [diff] [blame] | 288 | def __init__(self, option, section, rawval): |
Fred Drake | e2c6491 | 2002-12-31 17:23:27 +0000 | [diff] [blame] | 289 | msg = ("Value interpolation too deeply recursive:\n" |
| 290 | "\tsection: [%s]\n" |
| 291 | "\toption : %s\n" |
| 292 | "\trawval : %s\n" |
| 293 | % (section, option, rawval)) |
| 294 | InterpolationError.__init__(self, option, section, msg) |
Michael Foord | bd6c079 | 2010-07-25 23:09:25 +0000 | [diff] [blame] | 295 | self.args = (option, section, rawval) |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 296 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 297 | |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 298 | class ParsingError(Error): |
Fred Drake | 8d5dd98 | 2002-12-30 23:51:45 +0000 | [diff] [blame] | 299 | """Raised when a configuration file does not follow legal syntax.""" |
| 300 | |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 301 | def __init__(self, source=None, filename=None): |
| 302 | # Exactly one of `source'/`filename' arguments has to be given. |
| 303 | # `filename' kept for compatibility. |
| 304 | if filename and source: |
| 305 | raise ValueError("Cannot specify both `filename' and `source'. " |
| 306 | "Use `source'.") |
| 307 | elif not filename and not source: |
| 308 | raise ValueError("Required argument `source' not given.") |
| 309 | elif filename: |
| 310 | source = filename |
| 311 | Error.__init__(self, 'Source contains parsing errors: %s' % source) |
| 312 | self.source = source |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 313 | self.errors = [] |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 314 | self.args = (source, ) |
| 315 | |
| 316 | @property |
| 317 | def filename(self): |
| 318 | """Deprecated, use `source'.""" |
| 319 | warnings.warn( |
| 320 | "This 'filename' attribute will be removed in future versions. " |
| 321 | "Use 'source' instead.", |
| 322 | PendingDeprecationWarning, stacklevel=2 |
| 323 | ) |
| 324 | return self.source |
| 325 | |
| 326 | @filename.setter |
| 327 | def filename(self, value): |
| 328 | """Deprecated, user `source'.""" |
| 329 | warnings.warn( |
| 330 | "The 'filename' attribute will be removed in future versions. " |
| 331 | "Use 'source' instead.", |
| 332 | PendingDeprecationWarning, stacklevel=2 |
| 333 | ) |
| 334 | self.source = value |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 335 | |
| 336 | def append(self, lineno, line): |
| 337 | self.errors.append((lineno, line)) |
Fred Drake | e2c6491 | 2002-12-31 17:23:27 +0000 | [diff] [blame] | 338 | self.message += '\n\t[line %2d]: %s' % (lineno, line) |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 339 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 340 | |
Fred Drake | 2a37f9f | 2000-09-27 22:43:54 +0000 | [diff] [blame] | 341 | class MissingSectionHeaderError(ParsingError): |
Fred Drake | 8d5dd98 | 2002-12-30 23:51:45 +0000 | [diff] [blame] | 342 | """Raised when a key-value pair is found before any section header.""" |
| 343 | |
Fred Drake | 2a37f9f | 2000-09-27 22:43:54 +0000 | [diff] [blame] | 344 | def __init__(self, filename, lineno, line): |
| 345 | Error.__init__( |
| 346 | self, |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 347 | 'File contains no section headers.\nfile: %s, line: %d\n%r' % |
Fred Drake | 2a37f9f | 2000-09-27 22:43:54 +0000 | [diff] [blame] | 348 | (filename, lineno, line)) |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 349 | self.source = filename |
Fred Drake | 2a37f9f | 2000-09-27 22:43:54 +0000 | [diff] [blame] | 350 | self.lineno = lineno |
| 351 | self.line = line |
Michael Foord | bd6c079 | 2010-07-25 23:09:25 +0000 | [diff] [blame] | 352 | self.args = (filename, lineno, line) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 353 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 354 | |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 355 | # Used in parsers to denote selecting a backwards-compatible inline comment |
| 356 | # character behavior (; and # are comments at the start of a line, but ; only |
| 357 | # inline) |
| 358 | _COMPATIBLE = object() |
| 359 | |
| 360 | # Used in parser getters to indicate the default behaviour when a specific |
| 361 | # option is not found it to raise an exception. Created to enable `None' as |
| 362 | # a valid fallback value. |
| 363 | _UNSET = object() |
| 364 | |
| 365 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 366 | class RawConfigParser(MutableMapping): |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 367 | """ConfigParser that does not do interpolation.""" |
| 368 | |
| 369 | # Regular expressions for parsing section headers and options |
| 370 | _SECT_TMPL = r""" |
| 371 | \[ # [ |
| 372 | (?P<header>[^]]+) # very permissive! |
| 373 | \] # ] |
| 374 | """ |
| 375 | _OPT_TMPL = r""" |
| 376 | (?P<option>.*?) # very permissive! |
| 377 | \s*(?P<vi>{delim})\s* # any number of space/tab, |
| 378 | # followed by any of the |
| 379 | # allowed delimiters, |
| 380 | # followed by any space/tab |
| 381 | (?P<value>.*)$ # everything up to eol |
| 382 | """ |
| 383 | _OPT_NV_TMPL = r""" |
| 384 | (?P<option>.*?) # very permissive! |
| 385 | \s*(?: # any number of space/tab, |
| 386 | (?P<vi>{delim})\s* # optionally followed by |
| 387 | # any of the allowed |
| 388 | # delimiters, followed by any |
| 389 | # space/tab |
| 390 | (?P<value>.*))?$ # everything up to eol |
| 391 | """ |
| 392 | |
| 393 | # Compiled regular expression for matching sections |
| 394 | SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE) |
| 395 | # Compiled regular expression for matching options with typical separators |
| 396 | OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE) |
| 397 | # Compiled regular expression for matching options with optional values |
| 398 | # delimited using typical separators |
| 399 | OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE) |
| 400 | # Compiled regular expression for matching leading whitespace in a line |
| 401 | NONSPACECRE = re.compile(r"\S") |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 402 | # Possible boolean values in the configuration. |
| 403 | BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True, |
| 404 | '0': False, 'no': False, 'false': False, 'off': False} |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 405 | |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 406 | def __init__(self, defaults=None, dict_type=_default_dict, |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 407 | allow_no_value=False, *, delimiters=('=', ':'), |
| 408 | comment_prefixes=_COMPATIBLE, strict=False, |
| 409 | empty_lines_in_values=True): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 410 | self._dict = dict_type |
| 411 | self._sections = self._dict() |
| 412 | self._defaults = self._dict() |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 413 | self._views = self._dict() |
| 414 | self._views[DEFAULTSECT] = SectionProxy(self, DEFAULTSECT) |
David Goodger | 68a1abd | 2004-10-03 15:40:25 +0000 | [diff] [blame] | 415 | if defaults: |
| 416 | for key, value in defaults.items(): |
| 417 | self._defaults[self.optionxform(key)] = value |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 418 | self._delimiters = tuple(delimiters) |
| 419 | if delimiters == ('=', ':'): |
| 420 | self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE |
| 421 | else: |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 422 | d = "|".join(re.escape(d) for d in delimiters) |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 423 | if allow_no_value: |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 424 | self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d), |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 425 | re.VERBOSE) |
| 426 | else: |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 427 | self._optcre = re.compile(self._OPT_TMPL.format(delim=d), |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 428 | re.VERBOSE) |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 429 | if comment_prefixes is _COMPATIBLE: |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 430 | self._startonly_comment_prefixes = ('#',) |
| 431 | self._comment_prefixes = (';',) |
| 432 | else: |
| 433 | self._startonly_comment_prefixes = () |
| 434 | self._comment_prefixes = tuple(comment_prefixes or ()) |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 435 | self._strict = strict |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 436 | self._allow_no_value = allow_no_value |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 437 | self._empty_lines_in_values = empty_lines_in_values |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 438 | |
| 439 | def defaults(self): |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 440 | return self._defaults |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 441 | |
| 442 | def sections(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 443 | """Return a list of section names, excluding [DEFAULT]""" |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 444 | # self._sections will never have [DEFAULT] in it |
Guido van Rossum | cc2b016 | 2007-02-11 06:12:03 +0000 | [diff] [blame] | 445 | return list(self._sections.keys()) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 446 | |
| 447 | def add_section(self, section): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 448 | """Create a new section in the configuration. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 449 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 450 | Raise DuplicateSectionError if a section by the specified name |
Christian Heimes | 90c3d9b | 2008-02-23 13:18:03 +0000 | [diff] [blame] | 451 | already exists. Raise ValueError if name is DEFAULT or any of it's |
| 452 | case-insensitive variants. |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 453 | """ |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 454 | if section.upper() == DEFAULTSECT: |
Christian Heimes | 90c3d9b | 2008-02-23 13:18:03 +0000 | [diff] [blame] | 455 | raise ValueError('Invalid section name: %s' % section) |
| 456 | |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 457 | if section in self._sections: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 458 | raise DuplicateSectionError(section) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 459 | self._sections[section] = self._dict() |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 460 | self._views[section] = SectionProxy(self, section) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 461 | |
| 462 | def has_section(self, section): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 463 | """Indicate whether the named section is present in the configuration. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 464 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 465 | The DEFAULT section is not acknowledged. |
| 466 | """ |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 467 | return section in self._sections |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 468 | |
| 469 | def options(self, section): |
Guido van Rossum | a5a24b7 | 1999-10-04 19:58:22 +0000 | [diff] [blame] | 470 | """Return a list of option names for the given section name.""" |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 471 | try: |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 472 | opts = self._sections[section].copy() |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 473 | except KeyError: |
| 474 | raise NoSectionError(section) |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 475 | opts.update(self._defaults) |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 476 | if '__name__' in opts: |
Fred Drake | 2a37f9f | 2000-09-27 22:43:54 +0000 | [diff] [blame] | 477 | del opts['__name__'] |
Guido van Rossum | cc2b016 | 2007-02-11 06:12:03 +0000 | [diff] [blame] | 478 | return list(opts.keys()) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 479 | |
Georg Brandl | 8dcaa73 | 2010-07-29 12:17:40 +0000 | [diff] [blame] | 480 | def read(self, filenames, encoding=None): |
Guido van Rossum | 6a8d84b | 1999-10-04 18:57:27 +0000 | [diff] [blame] | 481 | """Read and parse a filename or a list of filenames. |
Tim Peters | 88869f9 | 2001-01-14 23:36:06 +0000 | [diff] [blame] | 482 | |
Guido van Rossum | 6a8d84b | 1999-10-04 18:57:27 +0000 | [diff] [blame] | 483 | Files that cannot be opened are silently ignored; this is |
Barry Warsaw | 2539451 | 1999-10-12 16:12:48 +0000 | [diff] [blame] | 484 | designed so that you can specify a list of potential |
Guido van Rossum | 6a8d84b | 1999-10-04 18:57:27 +0000 | [diff] [blame] | 485 | configuration file locations (e.g. current directory, user's |
| 486 | home directory, systemwide directory), and all existing |
| 487 | configuration files in the list will be read. A single |
| 488 | filename may also be given. |
Fred Drake | 8290314 | 2004-05-18 04:24:02 +0000 | [diff] [blame] | 489 | |
| 490 | Return list of successfully read files. |
Guido van Rossum | 6a8d84b | 1999-10-04 18:57:27 +0000 | [diff] [blame] | 491 | """ |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 492 | if isinstance(filenames, str): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 493 | filenames = [filenames] |
Fred Drake | 8290314 | 2004-05-18 04:24:02 +0000 | [diff] [blame] | 494 | read_ok = [] |
Guido van Rossum | 6a8d84b | 1999-10-04 18:57:27 +0000 | [diff] [blame] | 495 | for filename in filenames: |
| 496 | try: |
Florent Xicluna | 42d5445 | 2010-09-22 22:35:38 +0000 | [diff] [blame] | 497 | with open(filename, encoding=encoding) as fp: |
| 498 | self._read(fp, filename) |
Guido van Rossum | 6a8d84b | 1999-10-04 18:57:27 +0000 | [diff] [blame] | 499 | except IOError: |
| 500 | continue |
Fred Drake | 8290314 | 2004-05-18 04:24:02 +0000 | [diff] [blame] | 501 | read_ok.append(filename) |
| 502 | return read_ok |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 503 | |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 504 | def read_file(self, f, source=None): |
Guido van Rossum | 6a8d84b | 1999-10-04 18:57:27 +0000 | [diff] [blame] | 505 | """Like read() but the argument must be a file-like object. |
| 506 | |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 507 | The `f' argument must have a `readline' method. Optional second |
| 508 | argument is the `source' specifying the name of the file being read. If |
| 509 | not given, it is taken from f.name. If `f' has no `name' attribute, |
| 510 | `<???>' is used. |
Guido van Rossum | 6a8d84b | 1999-10-04 18:57:27 +0000 | [diff] [blame] | 511 | """ |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 512 | if source is None: |
Guido van Rossum | 6a8d84b | 1999-10-04 18:57:27 +0000 | [diff] [blame] | 513 | try: |
Florent Xicluna | 42d5445 | 2010-09-22 22:35:38 +0000 | [diff] [blame] | 514 | source = f.name |
Guido van Rossum | 6a8d84b | 1999-10-04 18:57:27 +0000 | [diff] [blame] | 515 | except AttributeError: |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 516 | source = '<???>' |
| 517 | self._read(f, source) |
| 518 | |
| 519 | def read_string(self, string, source='<string>'): |
| 520 | """Read configuration from a given string.""" |
| 521 | sfile = io.StringIO(string) |
| 522 | self.read_file(sfile, source) |
| 523 | |
| 524 | def read_dict(self, dictionary, source='<dict>'): |
| 525 | """Read configuration from a dictionary. |
| 526 | |
| 527 | Keys are section names, values are dictionaries with keys and values |
| 528 | that should be present in the section. If the used dictionary type |
| 529 | preserves order, sections and their keys will be added in order. |
| 530 | |
| 531 | Optional second argument is the `source' specifying the name of the |
| 532 | dictionary being read. |
| 533 | """ |
| 534 | elements_added = set() |
| 535 | for section, keys in dictionary.items(): |
| 536 | try: |
| 537 | self.add_section(section) |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 538 | except (DuplicateSectionError, ValueError): |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 539 | if self._strict and section in elements_added: |
| 540 | raise |
| 541 | elements_added.add(section) |
| 542 | for key, value in keys.items(): |
| 543 | key = self.optionxform(key) |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 544 | if value is not None: |
| 545 | value = str(value) |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 546 | if self._strict and (section, key) in elements_added: |
| 547 | raise DuplicateOptionError(section, key, source) |
| 548 | elements_added.add((section, key)) |
| 549 | self.set(section, key, value) |
| 550 | |
| 551 | def readfp(self, fp, filename=None): |
| 552 | """Deprecated, use read_file instead.""" |
| 553 | warnings.warn( |
| 554 | "This method will be removed in future versions. " |
| 555 | "Use 'parser.read_file()' instead.", |
| 556 | PendingDeprecationWarning, stacklevel=2 |
| 557 | ) |
| 558 | self.read_file(fp, source=filename) |
Guido van Rossum | 6a8d84b | 1999-10-04 18:57:27 +0000 | [diff] [blame] | 559 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 560 | def get(self, section, option, *, vars=None, fallback=_UNSET): |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 561 | """Get an option value for a given section. |
| 562 | |
| 563 | If `vars' is provided, it must be a dictionary. The option is looked up |
| 564 | in `vars' (if provided), `section', and in `DEFAULTSECT' in that order. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 565 | If the key is not found and `fallback' is provided, it is used as |
| 566 | a fallback value. `None' can be provided as a `fallback' value. |
| 567 | |
| 568 | Arguments `vars' and `fallback' are keyword only. |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 569 | """ |
| 570 | try: |
| 571 | d = self._unify_values(section, vars) |
| 572 | except NoSectionError: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 573 | if fallback is _UNSET: |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 574 | raise |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 575 | else: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 576 | return fallback |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 577 | option = self.optionxform(option) |
| 578 | try: |
| 579 | return d[option] |
| 580 | except KeyError: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 581 | if fallback is _UNSET: |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 582 | raise NoOptionError(option, section) |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 583 | else: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 584 | return fallback |
Fred Drake | 2a37f9f | 2000-09-27 22:43:54 +0000 | [diff] [blame] | 585 | |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 586 | def items(self, section): |
Fred Drake | 2ca041f | 2002-09-27 15:49:56 +0000 | [diff] [blame] | 587 | try: |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 588 | d2 = self._sections[section] |
Fred Drake | 2ca041f | 2002-09-27 15:49:56 +0000 | [diff] [blame] | 589 | except KeyError: |
| 590 | if section != DEFAULTSECT: |
| 591 | raise NoSectionError(section) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 592 | d2 = self._dict() |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 593 | d = self._defaults.copy() |
| 594 | d.update(d2) |
Fred Drake | df393bd | 2002-10-25 20:41:30 +0000 | [diff] [blame] | 595 | if "__name__" in d: |
| 596 | del d["__name__"] |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 597 | return d.items() |
Fred Drake | 2ca041f | 2002-09-27 15:49:56 +0000 | [diff] [blame] | 598 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 599 | def _get(self, section, conv, option, **kwargs): |
| 600 | return conv(self.get(section, option, **kwargs)) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 601 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 602 | def getint(self, section, option, *, vars=None, fallback=_UNSET): |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 603 | try: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 604 | return self._get(section, int, option, vars=vars) |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 605 | except (NoSectionError, NoOptionError): |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 606 | if fallback is _UNSET: |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 607 | raise |
| 608 | else: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 609 | return fallback |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 610 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 611 | def getfloat(self, section, option, *, vars=None, fallback=_UNSET): |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 612 | try: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 613 | return self._get(section, float, option, vars=vars) |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 614 | except (NoSectionError, NoOptionError): |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 615 | if fallback is _UNSET: |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 616 | raise |
| 617 | else: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 618 | return fallback |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 619 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 620 | def getboolean(self, section, option, *, vars=None, fallback=_UNSET): |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 621 | try: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 622 | return self._get(section, self._convert_to_boolean, option, |
| 623 | vars=vars) |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 624 | except (NoSectionError, NoOptionError): |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 625 | if fallback is _UNSET: |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 626 | raise |
| 627 | else: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 628 | return fallback |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 629 | |
Guido van Rossum | 9e480ad | 1999-06-17 18:41:42 +0000 | [diff] [blame] | 630 | def optionxform(self, optionstr): |
Eric S. Raymond | 9eb54d9 | 2001-02-09 05:19:09 +0000 | [diff] [blame] | 631 | return optionstr.lower() |
Guido van Rossum | 9e480ad | 1999-06-17 18:41:42 +0000 | [diff] [blame] | 632 | |
Eric S. Raymond | 417c489 | 2000-07-10 18:11:00 +0000 | [diff] [blame] | 633 | def has_option(self, section, option): |
| 634 | """Check for the existence of a given option in a given section.""" |
Fred Drake | c2ff905 | 2002-09-27 15:33:11 +0000 | [diff] [blame] | 635 | if not section or section == DEFAULTSECT: |
| 636 | option = self.optionxform(option) |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 637 | return option in self._defaults |
| 638 | elif section not in self._sections: |
Neal Norwitz | f680cc4 | 2002-12-17 01:56:47 +0000 | [diff] [blame] | 639 | return False |
Eric S. Raymond | 417c489 | 2000-07-10 18:11:00 +0000 | [diff] [blame] | 640 | else: |
Fred Drake | 3c823aa | 2001-02-26 21:55:34 +0000 | [diff] [blame] | 641 | option = self.optionxform(option) |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 642 | return (option in self._sections[section] |
| 643 | or option in self._defaults) |
Eric S. Raymond | 417c489 | 2000-07-10 18:11:00 +0000 | [diff] [blame] | 644 | |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 645 | def set(self, section, option, value=None): |
Eric S. Raymond | 417c489 | 2000-07-10 18:11:00 +0000 | [diff] [blame] | 646 | """Set an option.""" |
Fred Drake | c2ff905 | 2002-09-27 15:33:11 +0000 | [diff] [blame] | 647 | if not section or section == DEFAULTSECT: |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 648 | sectdict = self._defaults |
Eric S. Raymond | 417c489 | 2000-07-10 18:11:00 +0000 | [diff] [blame] | 649 | else: |
| 650 | try: |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 651 | sectdict = self._sections[section] |
Eric S. Raymond | 417c489 | 2000-07-10 18:11:00 +0000 | [diff] [blame] | 652 | except KeyError: |
| 653 | raise NoSectionError(section) |
Fred Drake | c2ff905 | 2002-09-27 15:33:11 +0000 | [diff] [blame] | 654 | sectdict[self.optionxform(option)] = value |
Eric S. Raymond | 417c489 | 2000-07-10 18:11:00 +0000 | [diff] [blame] | 655 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 656 | def write(self, fp, space_around_delimiters=True): |
| 657 | """Write an .ini-format representation of the configuration state. |
| 658 | |
| 659 | If `space_around_delimiters' is True (the default), delimiters |
| 660 | between keys and values are surrounded by spaces. |
| 661 | """ |
| 662 | if space_around_delimiters: |
| 663 | d = " {} ".format(self._delimiters[0]) |
| 664 | else: |
| 665 | d = self._delimiters[0] |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 666 | if self._defaults: |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 667 | self._write_section(fp, DEFAULTSECT, self._defaults.items(), d) |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 668 | for section in self._sections: |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 669 | self._write_section(fp, section, |
| 670 | self._sections[section].items(), d) |
| 671 | |
| 672 | def _write_section(self, fp, section_name, section_items, delimiter): |
| 673 | """Write a single section to the specified `fp'.""" |
| 674 | fp.write("[{}]\n".format(section_name)) |
| 675 | for key, value in section_items: |
| 676 | if key == "__name__": |
| 677 | continue |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 678 | if value is not None or not self._allow_no_value: |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 679 | value = delimiter + str(value).replace('\n', '\n\t') |
| 680 | else: |
| 681 | value = "" |
| 682 | fp.write("{}{}\n".format(key, value)) |
| 683 | fp.write("\n") |
Eric S. Raymond | 417c489 | 2000-07-10 18:11:00 +0000 | [diff] [blame] | 684 | |
Thomas Wouters | ff4df6d | 2000-07-21 05:19:59 +0000 | [diff] [blame] | 685 | def remove_option(self, section, option): |
Eric S. Raymond | 649685a | 2000-07-14 14:28:22 +0000 | [diff] [blame] | 686 | """Remove an option.""" |
Fred Drake | c2ff905 | 2002-09-27 15:33:11 +0000 | [diff] [blame] | 687 | if not section or section == DEFAULTSECT: |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 688 | sectdict = self._defaults |
Eric S. Raymond | 649685a | 2000-07-14 14:28:22 +0000 | [diff] [blame] | 689 | else: |
| 690 | try: |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 691 | sectdict = self._sections[section] |
Eric S. Raymond | 649685a | 2000-07-14 14:28:22 +0000 | [diff] [blame] | 692 | except KeyError: |
| 693 | raise NoSectionError(section) |
Fred Drake | 3c823aa | 2001-02-26 21:55:34 +0000 | [diff] [blame] | 694 | option = self.optionxform(option) |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 695 | existed = option in sectdict |
Eric S. Raymond | 649685a | 2000-07-14 14:28:22 +0000 | [diff] [blame] | 696 | if existed: |
Fred Drake | ff4a23b | 2000-12-04 16:29:13 +0000 | [diff] [blame] | 697 | del sectdict[option] |
Eric S. Raymond | 649685a | 2000-07-14 14:28:22 +0000 | [diff] [blame] | 698 | return existed |
| 699 | |
Thomas Wouters | ff4df6d | 2000-07-21 05:19:59 +0000 | [diff] [blame] | 700 | def remove_section(self, section): |
Eric S. Raymond | 649685a | 2000-07-14 14:28:22 +0000 | [diff] [blame] | 701 | """Remove a file section.""" |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 702 | existed = section in self._sections |
Fred Drake | c2ff905 | 2002-09-27 15:33:11 +0000 | [diff] [blame] | 703 | if existed: |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 704 | del self._sections[section] |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 705 | del self._views[section] |
Fred Drake | c2ff905 | 2002-09-27 15:33:11 +0000 | [diff] [blame] | 706 | return existed |
Eric S. Raymond | 649685a | 2000-07-14 14:28:22 +0000 | [diff] [blame] | 707 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 708 | def __getitem__(self, key): |
| 709 | if key != DEFAULTSECT and not self.has_section(key): |
| 710 | raise KeyError(key) |
| 711 | return self._views[key] |
| 712 | |
| 713 | def __setitem__(self, key, value): |
| 714 | # To conform with the mapping protocol, overwrites existing values in |
| 715 | # the section. |
| 716 | |
| 717 | # XXX this is not atomic if read_dict fails at any point. Then again, |
| 718 | # no update method in configparser is atomic in this implementation. |
| 719 | self.remove_section(key) |
| 720 | self.read_dict({key: value}) |
| 721 | |
| 722 | def __delitem__(self, key): |
| 723 | if key == DEFAULTSECT: |
| 724 | raise ValueError("Cannot remove the default section.") |
| 725 | if not self.has_section(key): |
| 726 | raise KeyError(key) |
| 727 | self.remove_section(key) |
| 728 | |
| 729 | def __contains__(self, key): |
| 730 | return key == DEFAULTSECT or self.has_section(key) |
| 731 | |
| 732 | def __len__(self): |
| 733 | return len(self._sections) + 1 # the default section |
| 734 | |
| 735 | def __iter__(self): |
| 736 | # XXX does it break when underlying container state changed? |
| 737 | return itertools.chain((DEFAULTSECT,), self._sections.keys()) |
| 738 | |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 739 | def _read(self, fp, fpname): |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 740 | """Parse a sectioned configuration file. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 741 | |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 742 | Each section in a configuration file contains a header, indicated by |
| 743 | a name in square brackets (`[]'), plus key/value options, indicated by |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 744 | `name' and `value' delimited with a specific substring (`=' or `:' by |
| 745 | default). |
| 746 | |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 747 | Values can span multiple lines, as long as they are indented deeper |
| 748 | than the first line of the value. Depending on the parser's mode, blank |
| 749 | lines may be treated as parts of multiline values or ignored. |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 750 | |
| 751 | Configuration files may include comments, prefixed by specific |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 752 | characters (`#' and `;' by default). Comments may appear on their own |
| 753 | in an otherwise empty line or may be entered in lines holding values or |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 754 | section names. |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 755 | """ |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 756 | elements_added = set() |
Brian Curtin | 9a27b0c | 2010-07-26 00:27:10 +0000 | [diff] [blame] | 757 | cursect = None # None, or a dictionary |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 758 | sectname = None |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 759 | optname = None |
| 760 | lineno = 0 |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 761 | indent_level = 0 |
Brian Curtin | 9a27b0c | 2010-07-26 00:27:10 +0000 | [diff] [blame] | 762 | e = None # None, or an exception |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 763 | for lineno, line in enumerate(fp, start=1): |
Georg Brandl | f206d0e | 2010-07-29 11:56:20 +0000 | [diff] [blame] | 764 | # strip full line comments |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 765 | comment_start = None |
| 766 | for prefix in self._startonly_comment_prefixes: |
| 767 | if line.strip().startswith(prefix): |
| 768 | comment_start = 0 |
| 769 | break |
| 770 | # strip inline comments |
| 771 | for prefix in self._comment_prefixes: |
| 772 | index = line.find(prefix) |
| 773 | if index == 0 or (index > 0 and line[index-1].isspace()): |
| 774 | comment_start = index |
| 775 | break |
| 776 | value = line[:comment_start].strip() |
| 777 | if not value: |
Georg Brandl | f206d0e | 2010-07-29 11:56:20 +0000 | [diff] [blame] | 778 | if self._empty_lines_in_values: |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 779 | # add empty line to the value, but only if there was no |
| 780 | # comment on the line |
Georg Brandl | f206d0e | 2010-07-29 11:56:20 +0000 | [diff] [blame] | 781 | if (comment_start is None and |
| 782 | cursect is not None and |
| 783 | optname and |
| 784 | cursect[optname] is not None): |
| 785 | cursect[optname].append('') # newlines added at join |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 786 | else: |
| 787 | # empty line marks end of value |
| 788 | indent_level = sys.maxsize |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 789 | continue |
| 790 | # continuation line? |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 791 | first_nonspace = self.NONSPACECRE.search(line) |
| 792 | cur_indent_level = first_nonspace.start() if first_nonspace else 0 |
| 793 | if (cursect is not None and optname and |
| 794 | cur_indent_level > indent_level): |
| 795 | cursect[optname].append(value) |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 796 | # a section header or option header? |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 797 | else: |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 798 | indent_level = cur_indent_level |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 799 | # is it a section header? |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 800 | mo = self.SECTCRE.match(value) |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 801 | if mo: |
| 802 | sectname = mo.group('header') |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 803 | if sectname in self._sections: |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 804 | if self._strict and sectname in elements_added: |
| 805 | raise DuplicateSectionError(sectname, fpname, |
| 806 | lineno) |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 807 | cursect = self._sections[sectname] |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 808 | elements_added.add(sectname) |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 809 | elif sectname == DEFAULTSECT: |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 810 | cursect = self._defaults |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 811 | else: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 812 | cursect = self._dict() |
| 813 | cursect['__name__'] = sectname |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 814 | self._sections[sectname] = cursect |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 815 | self._views[sectname] = SectionProxy(self, sectname) |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 816 | elements_added.add(sectname) |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 817 | # So sections can't start with a continuation line |
| 818 | optname = None |
| 819 | # no section header in the file? |
| 820 | elif cursect is None: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 821 | raise MissingSectionHeaderError(fpname, lineno, line) |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 822 | # an option line? |
| 823 | else: |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 824 | mo = self._optcre.match(value) |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 825 | if mo: |
Fred Drake | c517b9b | 2000-02-28 20:59:03 +0000 | [diff] [blame] | 826 | optname, vi, optval = mo.group('option', 'vi', 'value') |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 827 | if not optname: |
| 828 | e = self._handle_error(e, fpname, lineno, line) |
Brian Curtin | 9a27b0c | 2010-07-26 00:27:10 +0000 | [diff] [blame] | 829 | optname = self.optionxform(optname.rstrip()) |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 830 | if (self._strict and |
| 831 | (sectname, optname) in elements_added): |
| 832 | raise DuplicateOptionError(sectname, optname, |
| 833 | fpname, lineno) |
| 834 | elements_added.add((sectname, optname)) |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 835 | # This check is fine because the OPTCRE cannot |
| 836 | # match if it would set optval to None |
| 837 | if optval is not None: |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 838 | optval = optval.strip() |
Brian Curtin | 9a27b0c | 2010-07-26 00:27:10 +0000 | [diff] [blame] | 839 | # allow empty values |
| 840 | if optval == '""': |
| 841 | optval = '' |
| 842 | cursect[optname] = [optval] |
| 843 | else: |
| 844 | # valueless option handling |
| 845 | cursect[optname] = optval |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 846 | else: |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 847 | # a non-fatal parsing error occurred. set up the |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 848 | # exception but keep going. the exception will be |
| 849 | # raised at the end of the file and will contain a |
| 850 | # list of all bogus lines |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 851 | e = self._handle_error(e, fpname, lineno, line) |
Barry Warsaw | bfa3f6b | 1998-07-01 20:41:12 +0000 | [diff] [blame] | 852 | # if any parsing errors occurred, raise an exception |
| 853 | if e: |
| 854 | raise e |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 855 | self._join_multiline_values() |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 856 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 857 | def _join_multiline_values(self): |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 858 | all_sections = itertools.chain((self._defaults,), |
| 859 | self._sections.values()) |
Brian Curtin | 9a27b0c | 2010-07-26 00:27:10 +0000 | [diff] [blame] | 860 | for options in all_sections: |
| 861 | for name, val in options.items(): |
| 862 | if isinstance(val, list): |
Georg Brandl | f206d0e | 2010-07-29 11:56:20 +0000 | [diff] [blame] | 863 | options[name] = '\n'.join(val).rstrip() |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 864 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 865 | def _handle_error(self, exc, fpname, lineno, line): |
| 866 | if not exc: |
| 867 | exc = ParsingError(fpname) |
| 868 | exc.append(lineno, repr(line)) |
| 869 | return exc |
| 870 | |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 871 | def _unify_values(self, section, vars): |
| 872 | """Create a copy of the DEFAULTSECT with values from a specific |
| 873 | `section' and the `vars' dictionary. If provided, values in `vars' |
| 874 | take precendence. |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 875 | """ |
| 876 | d = self._defaults.copy() |
| 877 | try: |
| 878 | d.update(self._sections[section]) |
| 879 | except KeyError: |
| 880 | if section != DEFAULTSECT: |
| 881 | raise NoSectionError(section) |
| 882 | # Update with the entry specific variables |
David Goodger | 68a1abd | 2004-10-03 15:40:25 +0000 | [diff] [blame] | 883 | if vars: |
| 884 | for key, value in vars.items(): |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 885 | if value is not None: |
| 886 | value = str(value) |
David Goodger | 68a1abd | 2004-10-03 15:40:25 +0000 | [diff] [blame] | 887 | d[self.optionxform(key)] = value |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 888 | return d |
| 889 | |
| 890 | def _convert_to_boolean(self, value): |
| 891 | """Return a boolean value translating from other types if necessary. |
| 892 | """ |
| 893 | if value.lower() not in self.BOOLEAN_STATES: |
| 894 | raise ValueError('Not a boolean: %s' % value) |
| 895 | return self.BOOLEAN_STATES[value.lower()] |
| 896 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 897 | def _validate_value_type(self, value): |
| 898 | """Raises a TypeError for non-string values. |
| 899 | |
| 900 | The only legal non-string value if we allow valueless |
| 901 | options is None, so we need to check if the value is a |
| 902 | string if: |
| 903 | - we do not allow valueless options, or |
| 904 | - we allow valueless options but the value is not None |
| 905 | |
| 906 | For compatibility reasons this method is not used in classic set() |
| 907 | for RawConfigParsers and ConfigParsers. It is invoked in every |
| 908 | case for mapping protocol access and in SafeConfigParser.set(). |
| 909 | """ |
| 910 | if not self._allow_no_value or value: |
| 911 | if not isinstance(value, str): |
| 912 | raise TypeError("option values must be strings") |
| 913 | |
| 914 | |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 915 | |
| 916 | class ConfigParser(RawConfigParser): |
| 917 | """ConfigParser implementing interpolation.""" |
| 918 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 919 | def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET): |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 920 | """Get an option value for a given section. |
| 921 | |
| 922 | If `vars' is provided, it must be a dictionary. The option is looked up |
| 923 | in `vars' (if provided), `section', and in `DEFAULTSECT' in that order. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 924 | If the key is not found and `fallback' is provided, it is used as |
| 925 | a fallback value. `None' can be provided as a `fallback' value. |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 926 | |
| 927 | All % interpolations are expanded in the return values, unless the |
| 928 | optional argument `raw' is true. Values for interpolation keys are |
| 929 | looked up in the same manner as the option. |
| 930 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 931 | Arguments `raw', `vars', and `fallback' are keyword only. |
| 932 | |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 933 | The section DEFAULT is special. |
| 934 | """ |
| 935 | try: |
| 936 | d = self._unify_values(section, vars) |
| 937 | except NoSectionError: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 938 | if fallback is _UNSET: |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 939 | raise |
| 940 | else: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 941 | return fallback |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 942 | option = self.optionxform(option) |
| 943 | try: |
| 944 | value = d[option] |
| 945 | except KeyError: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 946 | if fallback is _UNSET: |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 947 | raise NoOptionError(option, section) |
| 948 | else: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 949 | return fallback |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 950 | |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 951 | if raw or value is None: |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 952 | return value |
| 953 | else: |
| 954 | return self._interpolate(section, option, value, d) |
| 955 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 956 | def getint(self, section, option, *, raw=False, vars=None, |
| 957 | fallback=_UNSET): |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 958 | try: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 959 | return self._get(section, int, option, raw=raw, vars=vars) |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 960 | except (NoSectionError, NoOptionError): |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 961 | if fallback is _UNSET: |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 962 | raise |
| 963 | else: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 964 | return fallback |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 965 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 966 | def getfloat(self, section, option, *, raw=False, vars=None, |
| 967 | fallback=_UNSET): |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 968 | try: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 969 | return self._get(section, float, option, raw=raw, vars=vars) |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 970 | except (NoSectionError, NoOptionError): |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 971 | if fallback is _UNSET: |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 972 | raise |
| 973 | else: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 974 | return fallback |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 975 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 976 | def getboolean(self, section, option, *, raw=False, vars=None, |
| 977 | fallback=_UNSET): |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 978 | try: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 979 | return self._get(section, self._convert_to_boolean, option, |
| 980 | raw=raw, vars=vars) |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 981 | except (NoSectionError, NoOptionError): |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 982 | if fallback is _UNSET: |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 983 | raise |
| 984 | else: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 985 | return fallback |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 986 | |
Neal Norwitz | f680cc4 | 2002-12-17 01:56:47 +0000 | [diff] [blame] | 987 | def items(self, section, raw=False, vars=None): |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 988 | """Return a list of (name, value) tuples for each option in a section. |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 989 | |
| 990 | All % interpolations are expanded in the return values, based on the |
| 991 | defaults passed into the constructor, unless the optional argument |
| 992 | `raw' is true. Additional substitutions may be provided using the |
| 993 | `vars' argument, which must be a dictionary whose contents overrides |
| 994 | any pre-existing defaults. |
| 995 | |
| 996 | The section DEFAULT is special. |
| 997 | """ |
| 998 | d = self._defaults.copy() |
| 999 | try: |
| 1000 | d.update(self._sections[section]) |
| 1001 | except KeyError: |
| 1002 | if section != DEFAULTSECT: |
| 1003 | raise NoSectionError(section) |
| 1004 | # Update with the entry specific variables |
| 1005 | if vars: |
David Goodger | 68a1abd | 2004-10-03 15:40:25 +0000 | [diff] [blame] | 1006 | for key, value in vars.items(): |
| 1007 | d[self.optionxform(key)] = value |
Guido van Rossum | cc2b016 | 2007-02-11 06:12:03 +0000 | [diff] [blame] | 1008 | options = list(d.keys()) |
Fred Drake | df393bd | 2002-10-25 20:41:30 +0000 | [diff] [blame] | 1009 | if "__name__" in options: |
| 1010 | options.remove("__name__") |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 1011 | if raw: |
Fred Drake | 8c4da53 | 2003-10-21 16:45:00 +0000 | [diff] [blame] | 1012 | return [(option, d[option]) |
| 1013 | for option in options] |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 1014 | else: |
Fred Drake | 8c4da53 | 2003-10-21 16:45:00 +0000 | [diff] [blame] | 1015 | return [(option, self._interpolate(section, option, d[option], d)) |
| 1016 | for option in options] |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 1017 | |
| 1018 | def _interpolate(self, section, option, rawval, vars): |
| 1019 | # do the string interpolation |
| 1020 | value = rawval |
Tim Peters | 230a60c | 2002-11-09 05:08:07 +0000 | [diff] [blame] | 1021 | depth = MAX_INTERPOLATION_DEPTH |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 1022 | while depth: # Loop through this until it's done |
| 1023 | depth -= 1 |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 1024 | if value and "%(" in value: |
Fred Drake | bc12b01 | 2004-05-18 02:25:51 +0000 | [diff] [blame] | 1025 | value = self._KEYCRE.sub(self._interpolation_replace, value) |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 1026 | try: |
| 1027 | value = value % vars |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 1028 | except KeyError as e: |
Fred Drake | e2c6491 | 2002-12-31 17:23:27 +0000 | [diff] [blame] | 1029 | raise InterpolationMissingOptionError( |
Brett Cannon | ca477b2 | 2007-03-21 22:26:20 +0000 | [diff] [blame] | 1030 | option, section, rawval, e.args[0]) |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 1031 | else: |
| 1032 | break |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 1033 | if value and "%(" in value: |
Fred Drake | fce6557 | 2002-10-25 18:08:18 +0000 | [diff] [blame] | 1034 | raise InterpolationDepthError(option, section, rawval) |
| 1035 | return value |
Fred Drake | 0eebd5c | 2002-10-25 21:52:00 +0000 | [diff] [blame] | 1036 | |
Fred Drake | bc12b01 | 2004-05-18 02:25:51 +0000 | [diff] [blame] | 1037 | _KEYCRE = re.compile(r"%\(([^)]*)\)s|.") |
| 1038 | |
| 1039 | def _interpolation_replace(self, match): |
| 1040 | s = match.group(1) |
| 1041 | if s is None: |
| 1042 | return match.group() |
| 1043 | else: |
| 1044 | return "%%(%s)s" % self.optionxform(s) |
| 1045 | |
Fred Drake | 0eebd5c | 2002-10-25 21:52:00 +0000 | [diff] [blame] | 1046 | |
| 1047 | class SafeConfigParser(ConfigParser): |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 1048 | """ConfigParser implementing sane interpolation.""" |
Fred Drake | 0eebd5c | 2002-10-25 21:52:00 +0000 | [diff] [blame] | 1049 | |
| 1050 | def _interpolate(self, section, option, rawval, vars): |
| 1051 | # do the string interpolation |
| 1052 | L = [] |
| 1053 | self._interpolate_some(option, L, rawval, section, vars, 1) |
| 1054 | return ''.join(L) |
| 1055 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1056 | _interpvar_re = re.compile(r"%\(([^)]+)\)s") |
Fred Drake | 0eebd5c | 2002-10-25 21:52:00 +0000 | [diff] [blame] | 1057 | |
| 1058 | def _interpolate_some(self, option, accum, rest, section, map, depth): |
| 1059 | if depth > MAX_INTERPOLATION_DEPTH: |
| 1060 | raise InterpolationDepthError(option, section, rest) |
| 1061 | while rest: |
| 1062 | p = rest.find("%") |
| 1063 | if p < 0: |
| 1064 | accum.append(rest) |
| 1065 | return |
| 1066 | if p > 0: |
| 1067 | accum.append(rest[:p]) |
| 1068 | rest = rest[p:] |
| 1069 | # p is no longer used |
| 1070 | c = rest[1:2] |
| 1071 | if c == "%": |
| 1072 | accum.append("%") |
| 1073 | rest = rest[2:] |
| 1074 | elif c == "(": |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1075 | m = self._interpvar_re.match(rest) |
Fred Drake | 0eebd5c | 2002-10-25 21:52:00 +0000 | [diff] [blame] | 1076 | if m is None: |
Neal Norwitz | 10f3018 | 2003-06-29 04:23:35 +0000 | [diff] [blame] | 1077 | raise InterpolationSyntaxError(option, section, |
| 1078 | "bad interpolation variable reference %r" % rest) |
Fred Drake | bc12b01 | 2004-05-18 02:25:51 +0000 | [diff] [blame] | 1079 | var = self.optionxform(m.group(1)) |
Fred Drake | 0eebd5c | 2002-10-25 21:52:00 +0000 | [diff] [blame] | 1080 | rest = rest[m.end():] |
| 1081 | try: |
| 1082 | v = map[var] |
| 1083 | except KeyError: |
Fred Drake | e2c6491 | 2002-12-31 17:23:27 +0000 | [diff] [blame] | 1084 | raise InterpolationMissingOptionError( |
| 1085 | option, section, rest, var) |
Fred Drake | 0eebd5c | 2002-10-25 21:52:00 +0000 | [diff] [blame] | 1086 | if "%" in v: |
| 1087 | self._interpolate_some(option, accum, v, |
| 1088 | section, map, depth + 1) |
| 1089 | else: |
| 1090 | accum.append(v) |
| 1091 | else: |
| 1092 | raise InterpolationSyntaxError( |
Neal Norwitz | 10f3018 | 2003-06-29 04:23:35 +0000 | [diff] [blame] | 1093 | option, section, |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 1094 | "'%%' must be followed by '%%' or '(', " |
| 1095 | "found: %r" % (rest,)) |
David Goodger | 1cbf206 | 2004-10-03 15:55:09 +0000 | [diff] [blame] | 1096 | |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 1097 | def set(self, section, option, value=None): |
David Goodger | 1cbf206 | 2004-10-03 15:55:09 +0000 | [diff] [blame] | 1098 | """Set an option. Extend ConfigParser.set: check for string values.""" |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1099 | self._validate_value_type(value) |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 1100 | # check for bad percent signs |
| 1101 | if value: |
| 1102 | tmp_value = value.replace('%%', '') # escaped percent signs |
| 1103 | tmp_value = self._interpvar_re.sub('', tmp_value) # valid syntax |
| 1104 | if '%' in tmp_value: |
| 1105 | raise ValueError("invalid interpolation syntax in %r at " |
| 1106 | "position %d" % (value, tmp_value.find('%'))) |
David Goodger | 1cbf206 | 2004-10-03 15:55:09 +0000 | [diff] [blame] | 1107 | ConfigParser.set(self, section, option, value) |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1108 | |
| 1109 | |
| 1110 | class SectionProxy(MutableMapping): |
| 1111 | """A proxy for a single section from a parser.""" |
| 1112 | |
| 1113 | _noname = ("__name__ special key access and modification " |
| 1114 | "not supported through the mapping interface.") |
| 1115 | |
| 1116 | def __init__(self, parser, section_name): |
| 1117 | """Creates a view on a section named `section_name` in `parser`.""" |
| 1118 | self._parser = parser |
| 1119 | self._section = section_name |
| 1120 | self.getint = functools.partial(self._parser.getint, |
| 1121 | self._section) |
| 1122 | self.getfloat = functools.partial(self._parser.getfloat, |
| 1123 | self._section) |
| 1124 | self.getboolean = functools.partial(self._parser.getboolean, |
| 1125 | self._section) |
| 1126 | |
| 1127 | def __repr__(self): |
| 1128 | return '<Section: {}>'.format(self._section) |
| 1129 | |
| 1130 | def __getitem__(self, key): |
| 1131 | if key == '__name__': |
| 1132 | raise ValueError(self._noname) |
| 1133 | if not self._parser.has_option(self._section, key): |
| 1134 | raise KeyError(key) |
| 1135 | return self._parser.get(self._section, key) |
| 1136 | |
| 1137 | def __setitem__(self, key, value): |
| 1138 | if key == '__name__': |
| 1139 | raise ValueError(self._noname) |
| 1140 | self._parser._validate_value_type(value) |
| 1141 | return self._parser.set(self._section, key, value) |
| 1142 | |
| 1143 | def __delitem__(self, key): |
| 1144 | if key == '__name__': |
| 1145 | raise ValueError(self._noname) |
| 1146 | if not self._parser.has_option(self._section, key): |
| 1147 | raise KeyError(key) |
| 1148 | return self._parser.remove_option(self._section, key) |
| 1149 | |
| 1150 | def __contains__(self, key): |
| 1151 | if key == '__name__': |
| 1152 | return False |
| 1153 | return self._parser.has_option(self._section, key) |
| 1154 | |
| 1155 | def __len__(self): |
| 1156 | # __name__ is properly hidden by .options() |
| 1157 | # XXX weak performance |
| 1158 | return len(self._parser.options(self._section)) |
| 1159 | |
| 1160 | def __iter__(self): |
| 1161 | # __name__ is properly hidden by .options() |
| 1162 | # XXX weak performance |
| 1163 | # XXX does not break when underlying container state changed |
| 1164 | return self._parser.options(self._section).__iter__() |