Python Glossary Русский

Python 3.2+configparserterm

configparser.BasicInterpolation

interpolation

ConfigParser's default interpolation: %(name)s inserts a key from the same section or from [DEFAULT]; a literal percent sign is written as %%.

Syntax

configparser.ConfigParser(interpolation=configparser.BasicInterpolation())

This is why '50%' or a password containing % fails with InterpolationSyntaxError — on get(), not when the file is read. Ways out: double the % in the file, use get(..., raw=True), or ConfigParser(interpolation=None). set('k', '5%') is rejected right away with ValueError. %(...)s cannot reach other sections; that is ExtendedInterpolation.

Examples

import configparser
cfg = configparser.ConfigParser()
cfg.read_string("[paths]\nhome = /home/ann\ndata = %(home)s/data\ngain = 80%%\n")
print(cfg.get("paths", "data"))  # → /home/ann/data
print(cfg.get("paths", "gain"))  # → 80%
print(cfg.get("paths", "data", raw=True))  # → %(home)s/data
import configparser
cfg = configparser.ConfigParser()
cfg.read_string("[db]\nrate = 50%\n")  # чтение проходит
try:
    cfg.get("db", "rate")
except configparser.InterpolationSyntaxError as e:
    print(type(e).__name__)  # → InterpolationSyntaxError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy