configparser.py 53 KB

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