Python Glossary Русский

Python 3.2+configparserterm

configparser.SectionProxy

section access

The section object returned by parser['name']: a live, dict-like view into the parser data with getint/getboolean helpers.

Syntax

section = parser['name']; section.get(option, fallback=None); section.getint(option)

It is not a copy: section['key'] = '1' changes the parser immediately. A missing section accessed with brackets raises KeyError, not NoSectionError, so except configparser.Error does not catch it. len() and iteration include the [DEFAULT] keys. Here get(option, fallback) takes the fallback as its second argument.

Examples

import configparser
cfg = configparser.ConfigParser()
cfg.read_string("[DEFAULT]\nlevel = info\n[db]\nport = 5432\n")
db = cfg["db"]
db["port"] = "6543"
print(cfg.get("db", "port"))  # → 6543 — секция живая, а не копия
print(len(db), db.get("host", "localhost"))  # → 2 localhost
try:
    cfg["cache"]
except KeyError as e:
    print("KeyError", e)  # → KeyError 'cache'

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy