01 / INVENTORY AND CONFIGURATION · LESSON 04

Read an INI configuration deliberately

Parse typed settings while preserving literal percent signs and rejecting ambiguous configuration.

15 min · learn at your pace

Configuration has a grammar

INI files organise named options into sections such as [service]. Python's configparser understands comments, section boundaries and option syntax. Splitting every line on an equals sign would make it easy to misread comments or values containing that character.

Use getboolean() and getint() for declared types. The standard boolean parser recognises values such as true/false, yes/no, on/off and 1/0. A successful conversion is only the first step: this service permits one to 64 workers, so validate that range separately.

Decide whether interpolation belongs in the tool

ConfigParser normally interprets percent-based substitutions. This export is data, so construct it with interpolation=None. A value like %TEMP%/logs should remain literal rather than cause an interpolation error or depend on another setting.

Require a service section with enabled, workers and log_path options; standard DEFAULT inheritance is allowed. Keep strict duplicate detection so two declarations of the same option do not silently override each other. Report malformed or incomplete configuration as ValueError to give the caller one clear failure contract.

This lesson reads a supplied text configuration. It does not start a service, expand environment variables or create a directory from the log path. Those strings stay data until a separate, explicitly authorised operation uses them.

Try an example.py
import configparser
config = configparser.ConfigParser(interpolation=None)
config.read_string("[service]\nenabled=yes\nworkers=4\nlog_path=%TEMP%/logs\n")
print(config.getboolean("service", "enabled"), config.get("service", "log_path"))
YOUR TURN

Put it into practice.

Define read_service_settings(text). Parse INI with interpolation disabled and strict duplicate handling. Read [service] enabled via getboolean, workers via getint, and stripped log_path. DEFAULT inheritance is allowed. Require workers 1–64 and a nonempty path. Return enabled (bool), workers (int), log_path (string). Missing/malformed settings, invalid conversions, duplicates and invalid ranges raise ValueError. Do not expand or use the path.

See an explained solution
One way to solve it.py
import configparser

def read_service_settings(text):
    parser = configparser.ConfigParser(interpolation=None)
    try:
        parser.read_string(text)
        enabled = parser.getboolean("service", "enabled")
        workers = parser.getint("service", "workers")
        log_path = parser.get("service", "log_path").strip()
        if not 1 <= workers <= 64 or not log_path:
            raise ValueError("Invalid service settings")
    except (configparser.Error, ValueError) as error:
        raise ValueError("Invalid service configuration") from error
    return {"enabled": enabled, "workers": workers, "log_path": log_path}

if __name__ == "__main__":
    from pathlib import Path
    print(read_service_settings(Path("service.ini").read_text(encoding="utf-8")))

The parser handles the file grammar while explicit validation enforces this service’s contract. Disabling interpolation keeps exported paths literal.