Config Files with configparser
Published by Brayan K
configparser is Python's standard-library tool for reading and writing INI files — plain-text configuration made of [sections] and key = value pairs — so you can keep settings out of your code and edit them by hand.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A parsed value is still text until you request a conversion
INI gives values names and sections; it does not give every value a Python type. Parse once, convert at the boundary, and validate the application’s constraints before using the settings. A setting that looks like false is still a nonempty string when accessed through the mapping interface.
from configparser import ConfigParser
config = ConfigParser()
config.read_string("""[worker]
retries = 3
enabled = false
""")
print(type(config["worker"]["retries"]).__name__)
print(config.getint("worker", "retries") + 1)
print(bool(config["worker"]["enabled"]))
print(config.getboolean("worker", "enabled"))
# ✅ Expected output:
# str
# 4
# True
# Falsebool(text) only asks whether the string is empty. getboolean understands supported spellings such as yes/no, true/false, on/off and 1/0 without treating every nonempty value as true. It rejects unfamiliar spellings rather than guessing.
from configparser import ConfigParser
config = ConfigParser()
config.read_dict({"worker": {"enabled": "sometimes"}})
config.getboolean("worker", "enabled")
# ✅ Expected error:
# ValueError: Not a boolean: sometimesgetint and getfloat convert numeric strings, but conversion alone does not enforce a sensible range. For example, an integer can still be negative when the application requires a positive retry count. Custom conversion failures can be translated into application-specific errors using Custom Exceptions & Exception Chaining.
Defaults participate in lookup before a fallback is considered
from configparser import ConfigParser
config = ConfigParser()
config.read_dict({"DEFAULT": {"retries": "2"}, "worker": {"enabled": "yes"}})
print(config.getint("worker", "retries", fallback=9))
config["worker"]["retries"] = "4"
print(config.getint("worker", "retries", fallback=9))
del config["worker"]["retries"]
print(config.getint("worker", "retries", fallback=9))
print(config.getint("worker", "timeout", fallback=9))
# ✅ Expected output:
# 2
# 4
# 2
# 9An inherited DEFAULT value is present for lookup, so it wins over fallback. Deleting a section’s local override reveals the inherited value again. A section proxy is a live view of the parser; assigning through it changes the configuration. It is not an independent dictionary copy.
from configparser import ConfigParser
config = ConfigParser()
config.read_dict({"DEFAULT": {"mode": "safe"}, "worker": {"mode": "fast", "name": "blue"}})
worker = config["worker"]
worker.clear()
print(sorted(worker.items()))
print(config["worker"]["mode"])
# ✅ Expected output:
# [('mode', 'safe')]
# safefrom configparser import ConfigParser
config = ConfigParser()
config.add_section("worker")
text_fallback = config.getint("worker", "retries", fallback="3")
number_fallback = config.getint("worker", "retries", fallback=3)
print(type(text_fallback).__name__)
print(type(number_fallback).__name__)
# ✅ Expected output:
# str
# intSupply a fallback with the type the caller expects. A fallback handles a missing value, not malformed text in an existing option: getint will still reject an existing nonnumeric value. Use fallback only when omission is allowed by the configuration contract.
Option names are normalized; section names remain case-sensitive
from configparser import ConfigParser
config = ConfigParser()
config.read_string("""[Worker]
RetryCount = 3
""")
print(list(config["Worker"]))
print(config["Worker"]["RETRYCOUNT"])
print(config.has_section("worker"))
# ✅ Expected output:
# ['retrycount']
# 3
# FalseThe default optionxform lowercases option names. Section names are case-sensitive. If an existing configuration format truly requires case-sensitive option names, set optionxform to str before reading it and apply that policy consistently. Do not change it halfway through a loaded configuration.
from configparser import ConfigParser
config = ConfigParser()
config.add_section("worker")
config.set("worker", "retries", 3)
# ✅ Expected error:
# TypeError: option values must be stringsWrite str(value) when deliberately storing a numeric setting through set. read_dict accepts non-string values by converting them to strings, but that convenience does not make the stored configuration typed. The distinction is why conversion belongs at the application boundary.
Interpolation substitutes configuration values, not environment variables
from configparser import ConfigParser
config = ConfigParser()
config.read_dict({"DEFAULT": {"name": "Asha"}, "message": {"text": "Hello %(name)s", "progress": "75%%"}})
print(config["message"]["text"])
config["DEFAULT"]["name"] = "Bo"
print(config["message"]["text"])
print(config["message"]["progress"])
print(config.get("message", "text", raw=True))
# ✅ Expected output:
# Hello Asha
# Hello Bo
# 75%
# Hello %(name)sBasic interpolation uses %(option)s references and %% for a literal percent sign. raw=True returns the stored text without substituting references. It does not automatically expand environment variables, user directories or shell expressions. For opaque values that should remain untouched, configure interpolation=None.
from configparser import ConfigParser
config = ConfigParser(interpolation=None)
config.read_dict({"message": {"text": "Progress: 75%"}})
print(config["message"]["text"])
# ✅ Expected output:
# Progress: 75%A missing interpolation reference is an error when the value is retrieved. Do not catch it and silently use a default unless that is the documented policy; a misspelled required setting should normally be fixed. For cross-section references, ConfigParser also offers ExtendedInterpolation with a different syntax. Choose one interpolation policy for the format you support.
Layer sources deliberately and distinguish optional files from required ones
from configparser import ConfigParser
config = ConfigParser()
config.read_string("""[worker]
retries = 2
enabled = yes
""")
config.read_string("""[worker]
retries = 5
""")
print(config.getint("worker", "retries"))
print(config.getboolean("worker", "enabled"))
# ✅ Expected output:
# 5
# TrueThe order of reads determines which value wins. Strict parsing rejects duplicate keys within one source by default, while a later source can intentionally override an earlier source. Keep the layering order visible instead of letting directory enumeration choose it.
read accepts filenames and ignores files it cannot open, returning the filenames it did read. That is useful for optional configuration. For a required file, open it explicitly and use read_file so a missing or unreadable file is an error. These examples use read_string and in-memory streams so their results do not depend on the machine’s files.
from configparser import ConfigParser
from io import StringIO
config = ConfigParser()
config.read_dict({"worker": {"enabled": "yes", "retries": "2"}})
config["worker"]["retries"] = "4"
stream = StringIO()
config.write(stream)
stream.seek(0)
restored = ConfigParser()
restored.read_file(stream)
print(restored.getint("worker", "retries"))
print(restored.getboolean("worker", "enabled"))
# ✅ Expected output:
# 4
# Truewrite serializes the parser’s settings; it is not a round-trip editor for original comments and formatting. Keep a backup or use a format-aware editing tool when preserving a person’s layout matters. Reading or writing INI does not encrypt secrets or make all settings valid.
Finish typed access with a deliberate missing-value policy
Read the worker’s enabled flag as a boolean and its limit as an integer. Use the numeric fallback only for the missing retries option.
from configparser import ConfigParser
config = ConfigParser()
config.read_dict({"worker": {"enabled": "off", "limit": "6"}})
print(config.___("worker", "enabled"))
print(config.___("worker", "limit"))
print(config.getint("worker", "retries", fallback=___))
# 👉 replace ___ with getboolean
# 👉 replace ___ with getint
# 👉 replace ___ with 2
# ✅ Expected output:
# False
# 6
# 2Accept only a usable worker configuration
Write read_worker(text), requiring a worker section with enabled and limit options. Convert enabled with getboolean and limit with getint, then require a limit from 1 through 50. Return a dictionary containing the typed values. Test a valid disabled worker with limit 8, then one with limit 0. Print the accepted dictionary and the range failure. Keep missing fields and malformed values visible instead of turning every error into a default.
from configparser import ConfigParser
def read_worker(text):
config = ConfigParser(interpolation=None)
config.read_string(text)
enabled = config.getboolean("worker", "enabled")
limit = config.getint("worker", "limit")
if not 1 <= limit <= 50:
raise ValueError("limit must be between 1 and 50")
return {"enabled": enabled, "limit": limit}
valid = """[worker]
enabled = no
limit = 8
"""
invalid = """[worker]
enabled = yes
limit = 0
"""
print(read_worker(valid))
try:
read_worker(invalid)
except ValueError as error:
print(str(error))
# ✅ Expected output:
# {'enabled': False, 'limit': 8}
# limit must be between 1 and 50The returned object is typed application data. ConfigParser remains responsible for parsing and conversion, while the function owns the worker’s allowed range.
Practice quiz
What does this program print? from configparser import ConfigParser c = ConfigParser() c.read_dict({"app": {"enabled": "false"}}) print(bool(c["app"]["enabled"])) print(c.getboolean("app", "enabled"))
- False False
- True True
- False True
- True False
Answer: True False. A nonempty string is truthy, but getboolean parses the supported value.
What does this program print? from configparser import ConfigParser c = ConfigParser() c.read_dict({"DEFAULT": {"n": "2"}, "app": {}}) print(c.getint("app", "n", fallback=9))
- 9
- 2
- None
- KeyError
Answer: 2. Inherited defaults are found before a fallback is needed.
What does this program print? from configparser import ConfigParser c = ConfigParser() c.add_section("app") print(type(c.getint("app", "n", fallback="3")).__name__)
- str
- int
- float
- NoneType
Answer: str. A missing-value fallback is returned unchanged.
What does the default option-name policy change?
- All section names become lowercase
- Every value becomes lowercase
- Option names are normalized to lowercase
- Only missing options are lowercased
Answer: Option names are normalized to lowercase. Section names remain case-sensitive under the default policy.
What does this program print? from configparser import ConfigParser c = ConfigParser() c.read_dict({"DEFAULT": {"n": "2"}, "app": {"n": "4"}}) del c["app"]["n"] print(c["app"]["n"])
- 4
- KeyError
- 2
- None
Answer: 2. Removing an override exposes the inherited default.
How should a required configuration file be read so opening errors remain visible?
- Ignore read’s result
- Always use fallback values
- Catch every exception and continue
- Open it explicitly and pass the file to read_file
Answer: Open it explicitly and pass the file to read_file. read intentionally tolerates files it cannot open, which suits optional sources.
What does this program print? from configparser import ConfigParser c = ConfigParser(interpolation=None) c.read_dict({"app": {"text": "75%"}}) print(c["app"]["text"])
- 75%%
- 75%
- InterpolationSyntaxError
- 0.75
Answer: 75%. Disabling interpolation leaves the percent character literal.
What still needs checking after getint returns a number?
- The application’s allowed range
- Whether the string is nonempty
- Whether read_string used a real disk file
- Whether every option is capitalized
Answer: The application’s allowed range. Syntactically valid integers can still violate domain rules.
Continue this course
- Previous: Serialization with pickle
- Next: Checkpoint: OOP & Standard Library — Combine abc, properties, custom exceptions and config in a build — then a quiz
- Quick reference: Python cheat sheet