configparser.py 53 KB

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