Require an INI section before reading settings
Also published in our Blogger archive.
A configuration reader can make its required structure explicit before it asks for individual options. Here, read_service_mode() calls has_section("service") immediately after parsing. If the section is absent, it raises a clear ValueError; otherwise it reads mode. The example exercises both paths: a valid document produces quiet, and a document containing only [logging] produces the predictable missing-section message.
This check is useful when a section represents a required component rather than an optional collection of settings. It distinguishes a missing section from a missing option, so an application can present a focused diagnostic or choose its own fallback behavior. The subsequent get() can still fail if mode itself is absent, and this helper intentionally does not validate whether the returned mode is one of an application's allowed values. Add that validation separately when the setting controls program behavior.
The parser's special DEFAULT values are not a substitute for an ordinary required section: defaults are inherited by normal sections, while has_section() checks for a named, explicitly present section. read_string() is available in Python 3.2+. The ConfigParser documentation describes INI sections and mapping-style access, including the role of defaults.
AI assistance disclosure: This article was drafted with AI assistance and should be reviewed alongside the application's error-handling policy.
import configparser
def read_service_mode(ini_text):
parser = configparser.ConfigParser()
parser.read_string(ini_text)
if not parser.has_section("service"):
raise ValueError("missing required section: service")
return parser.get("service", "mode")
mode = read_service_mode("[service]\nmode = quiet\n")
assert mode == "quiet"
try:
read_service_mode("[logging]\nlevel = info\n")
except ValueError as error:
missing_message = str(error)
else:
raise AssertionError("a missing service section must fail")
assert missing_message == "missing required section: service"
print("mode={0}".format(mode))
print("missing={0}".format(missing_message))
mode=quiet
missing=missing required section: service