Read a fallback value from DEFAULT in ConfigParser

ConfigParser has two similarly named mechanisms that behave differently. The special [DEFAULT] section supplies inherited option values to ordinary sections. The fallback= keyword of ConfigParser.get() is used only when the requested option is unavailable after normal lookup. A value in [DEFAULT] therefore takes precedence over a fallback= value.

This example reads an INI string with color = teal in [DEFAULT] and a separate [ui] section. parser.get("ui", "color", fallback="gray") returns teal: the section does not define color, so lookup inherits it from DEFAULT. The missing font option is absent from both places, so parser.get("ui", "font", fallback="sans") returns sans. The tuple assertion checks both concrete results, and the two printed lines make that precedence visible.

This inheritance can make configuration concise, but it also means a section may appear to contain an option that was not written under its own header. Do not use fallback= to override a value deliberately supplied by DEFAULT; select a different configuration design if per-call override semantics are needed. Values returned by get() are strings and may be interpolated by the default parser, so use getint(), getboolean(), a converter, or explicit validation when the application needs another type. The example uses read_string() solely for an in-memory fixture and does not test file-loading precedence.

This uses long-standing ConfigParser functionality available in supported Python 3 releases; no newer API is required. AI assistance disclosure: this article was drafted with AI assistance.

See the official configparser documentation.

import configparser

parser = configparser.ConfigParser()
parser.read_string(
    "[DEFAULT]\n"
    "color = teal\n"
    "\n"
    "[ui]\n"
    "theme = dark\n"
)

color = parser.get("ui", "color", fallback="gray")
font = parser.get("ui", "font", fallback="sans")

assert (color, font) == ("teal", "sans")
print(f"color={color}")
print(f"font={font}")
color=teal
font=sans

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic