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