Read an integer option from an INI string
Also published in our Blogger archive.
ConfigParser stores INI values as strings, even when a value looks numeric. Use getint() when the configuration option is specifically an integer: it retrieves the option and applies integer conversion in one call. This example parses a small INI document held entirely in memory, reads retries = 3 from the worker section, and asserts both the numeric value and its Python type before printing retries=3.
The input must name an existing section and option. A missing section raises a configuration-parser lookup error. An option missing from both the named section and its DEFAULT values also raises a lookup error; ConfigParser can inherit values from DEFAULT, so absence from worker alone does not necessarily fail. A present but non-integer value makes getint() raise ValueError. Those outcomes are useful signals when a setting is required; they are not silently converted to a default by this code. If an application accepts an optional setting, it can use the parser-level fallback= argument deliberately, then still validate the resulting value against its own rules.
read_string() lets the example avoid files and is available in Python 3.2+. The conversion only establishes that the text can be parsed as an integer; the assertions do not establish an appropriate retry policy, range, or behavior for negative values. The Python configparser documentation explains that values are stored as strings, documents getint() among the typed getters, and describes DEFAULT precedence.
AI assistance disclosure: This article was drafted with AI assistance and should be adapted to the application's configuration rules.
import configparser
ini_text = "[worker]\nretries = 3\n"
parser = configparser.ConfigParser()
parser.read_string(ini_text)
retries = parser.getint("worker", "retries")
assert retries == 3
assert isinstance(retries, int)
print("retries={0}".format(retries))
retries=3