Python Glossary Русский

Python 3.5+configparserterm

configparser.ConverterMapping

section access

The parser.converters mapping of name → conversion function. Adding a key such as list creates getlist() on the parser and on all of its sections.

Syntax

parser.converters['name'] = func  # или ConfigParser(converters={'name': func})

It is the supported way to get lists, paths or dates out of a string-only config without subclassing the parser. The converter receives the already interpolated string. Deleting the key removes the method too. The built-in int, float and boolean live in the same mapping, so they can be overridden.

Examples

import configparser
cfg = configparser.ConfigParser()
cfg.read_string("[app]\nhosts = a, b, c\n")
cfg.converters["list"] = lambda s: [x.strip() for x in s.split(",")]
print(cfg.getlist("app", "hosts"))  # → ['a', 'b', 'c']
print(cfg["app"].getlist("hosts"))  # → ['a', 'b', 'c']
print(sorted(cfg.converters))  # → ['boolean', 'float', 'int', 'list']
del cfg.converters["list"]
print(hasattr(cfg, "getlist"))  # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy