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