Resolve INI Settings and Defaults
Core idea
ConfigParser reads INI-style sections and string values. Section lookup can inherit values from DEFAULT; section-specific values override defaults. Use getint, getfloat or getboolean for explicit conversions. Interpolation resolves placeholders unless disabled.
import configparsercfg = configparser.ConfigParser()cfg.read_string("[DEFAULT]\nretries = 2\n[worker]\nretries = 5\n[backup]\n")print(cfg.getint("worker", "retries"), cfg.getint("backup", "retries"))The worker overrides the default; backup inherits it.
Choose literal values
import configparsercfg = configparser.ConfigParser(interpolation=None)cfg.read_string("[report]\nprogress = 50%\nenabled = yes\n")print(cfg["report"]["progress"], cfg.getboolean("report", "enabled"))Disabling interpolation keeps percent signs literal; getboolean recognizes yes.
Common mistake
bool("false") is True because the string is nonempty. Use getboolean for supported INI Boolean spellings; option names are lowercased by default.
Practice
Create DEFAULT with a timeout, override it in one section and compare getint for two sections.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
INI defaults and conversion
Check your understanding of ini configuration.
What is printed?
import configparserc=configparser.ConfigParser()c.read_string("[s]\nn=7\n")print(type(c["s"]["n"]).__name__)What is printed?
import configparserc=configparser.ConfigParser()c.read_string("[DEFAULT]\nactive=no\n[s]\n")print(c.getboolean("s","active"))Which value wins when a section defines an option also in DEFAULT?
Which constructor disables interpolation?