On this page
configparser
Prev: concurrent | Up: stdlib_module | Next: contextlib
Rel: csv, tomllib, netrc, plistlib
Ref: docs.python.org — configparser
Tags: #public #python3 #stdlib
Import
import configparser
Overview
Reads and writes classic INI-style configuration files ([section] + key = value) with typed getters (getint, getfloat, getboolean), fallback defaults, and optional value interpolation. Prefer tomllib for new Python projects (pyproject.toml, typed arrays/nested tables); reach for configparser for existing .ini/.cfg files (such as .gitconfig or setup.cfg).
Quick Start
import configparser
cfg = configparser.ConfigParser()
cfg.read_string('''
[server]
host = 127.0.0.1
port = 8080
debug = yes
''')
assert cfg["server"]["host"] == "127.0.0.1"
assert cfg.getint("server", "port") == 8080
assert cfg.getboolean("server", "debug") is True
Implementation Walkthrough
1. Reading with Safe Fallbacks & Writing Back to Disk
import configparser
import io
cfg = configparser.ConfigParser(interpolation=None)
cfg["app"] = {"mode": "prod", "workers": "4"}
assert cfg.getint("app", "timeout", fallback=30) == 30
buf = io.StringIO()
cfg.write(buf)
assert "[app]" in buf.getvalue()
2. Preserving Key Case
By default, ConfigParser lowercases all option keys; set cfg.optionxform = str before reading if case matters:
import configparser
cfg = configparser.ConfigParser()
cfg.optionxform = str
cfg.read_string("[env]\nAPI_KEY = demo\n")
assert "API_KEY" in cfg["env"]
Gotchas & Boundaries
cfg.read(path)silently ignores missing files: It returns a list of files successfully read—check that the list is non-empty, or usecfg.read_file(path.open(encoding="utf-8")).- All values are stored as strings: Use
getint(),getfloat(), andgetboolean()(recognizesyes/no,on/off,true/false,1/0). %triggersBasicInterpolationby default: Passinterpolation=Noneif values can contain literal%signs (URLs, format strings, passwords).- The
[DEFAULT]section injects its keys into every other section.
Classes & Objects
- configparser.BasicInterpolation — Interpolation as implemented in the classic ConfigParser. (Methods:
.before_get(),.before_read(),.before_set(),.before_write()) - configparser.ConfigParser — ConfigParser implementing interpolation. (Methods:
.add_section(),.clear(),.converters(),.defaults(),.get(),.getboolean()) - configparser.ConverterMapping — Enables reuse of get*() methods between the parser and section proxies. (Methods:
.clear(),.get(),.items(),.keys(),.pop(),.popitem()) - configparser.DuplicateOptionError — Raised by strict parsers when an option is repeated in an input source. (Methods:
.add_note(),.with_traceback()) - configparser.DuplicateSectionError — Raised when a section is repeated in an input source. (Methods:
.add_note(),.with_traceback()) - configparser.ExtendedInterpolation — Advanced variant of interpolation, supports the syntax used by
zc.buildout. Enables interpolation between sections. (Methods:.before_get(),.before_read(),.before_set(),.before_write()) - configparser.Interpolation — Dummy interpolation that passes the value through with no changes. (Methods:
.before_get(),.before_read(),.before_set(),.before_write()) - configparser.InterpolationDepthError — Raised when substitutions are nested too deeply. (Methods:
.add_note(),.with_traceback()) - configparser.InterpolationError — Base class for interpolation-related exceptions. (Methods:
.add_note(),.with_traceback()) - configparser.InterpolationMissingOptionError — A string substitution required a setting which was not available. (Methods:
.add_note(),.with_traceback()) - configparser.InterpolationSyntaxError — Raised when the source text contains invalid syntax. (Methods:
.add_note(),.with_traceback()) - configparser.InvalidWriteError — Raised when attempting to write data that the parser would read back differently. (Methods:
.add_note(),.with_traceback()) - configparser.MissingSectionHeaderError — Raised when a key-value pair is found before any section header. (Methods:
.add_note(),.append(),.combine(),.with_traceback()) - configparser.MultilineContinuationError — Raised when a key without value is followed by continuation line (Methods:
.add_note(),.append(),.combine(),.with_traceback()) - configparser.NoOptionError — A requested option was not found. (Methods:
.add_note(),.with_traceback()) - configparser.NoSectionError — Raised when no section matches a requested option. (Methods:
.add_note(),.with_traceback()) - configparser.ParsingError — Raised when a configuration file does not follow legal syntax. (Methods:
.add_note(),.append(),.combine(),.with_traceback()) - configparser.RawConfigParser — ConfigParser that does not do interpolation. (Methods:
.add_section(),.clear(),.converters(),.defaults(),.get(),.getboolean()) - configparser.SectionProxy — A proxy for a single section from a parser. (Methods:
.clear(),.get(),.items(),.keys(),.name(),.parser()) - configparser.UnnamedSectionDisabledError — Raised when an attempt to use UNNAMED_SECTION is made with the feature disabled. (Methods:
.add_note(),.with_traceback())
Constants & Attributes
configparser.DEFAULTSECT(str) ='DEFAULT'configparser.MAX_INTERPOLATION_DEPTH(int) =10configparser.UNNAMED_SECTION(_UnnamedSection) =<UNNAMED_SECTION>
Linked from
Related notes
- tuts/python3/stdlib_module/concurrent Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/csv Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/netrc Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/plistlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tomllib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/configparser/BasicInterpolation Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/configparser/ConfigParser Linked here; shared tags: #stdlib