ยปCore Development>Code coverage>Lib/configparser.py

Python code coverage for Lib/configparser.py

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