ConfigParser
Python
configuration files
list handling
programming tips

Lists in ConfigParser

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Python’s configparser reads INI values as strings, so lists are not a native type. To represent lists, you define a string convention and parse it explicitly. Teams often run into bugs when values contain spaces, commas inside items, or type conversions done inconsistently. A robust pattern standardizes list encoding format and centralizes parsing logic.

Core Sections

1. Store comma-separated values

INI example:

ini
[app]
hosts = api1.example.com, api2.example.com, api3.example.com

Parse with trimming:

python
1import configparser
2
3cfg = configparser.ConfigParser()
4cfg.read("settings.ini")
5
6hosts = [h.strip() for h in cfg["app"]["hosts"].split(",") if h.strip()]
7print(hosts)

2. Store JSON arrays for complex lists

For items that may include commas:

ini
[app]
features = ["alpha", "beta", "gamma"]
python
import json
features = json.loads(cfg["app"]["features"])

JSON avoids ambiguous delimiter parsing.

3. Typed list conversion helper

python
def get_int_list(section, key):
    raw = cfg[section][key]
    return [int(x.strip()) for x in raw.split(",") if x.strip()]

Central helpers keep parsing consistent across modules.

4. Defaults and missing keys

Use fallback values:

python
raw = cfg.get("app", "hosts", fallback="")
hosts = [h.strip() for h in raw.split(",") if h.strip()]

This prevents runtime failures on optional config.

5. Validation and error messages

Wrap parsing with meaningful exceptions that identify offending section/key and raw value.

python
1try:
2    ports = get_int_list("app", "ports")
3except ValueError as e:
4    raise ValueError("Invalid app.ports configuration") from e

6. When to choose another format

If configuration becomes deeply nested or heavily typed, YAML/TOML/JSON may be more maintainable than forcing complex data through INI strings.

Validation and production readiness

A working snippet is only the first step. To make the solution dependable, validate behavior under representative inputs and operating conditions. Build a small test matrix that includes normal cases, boundary values, and malformed data so failure modes are explicit. If the topic involves time, concurrency, or networking, add at least one test that simulates delayed execution and one test that verifies timeout handling. This catches race conditions and environment-specific bugs that rarely appear in local happy-path runs.

Operational clarity matters as much as correctness. Document assumptions near the implementation: runtime version, required dependencies, expected timezone or locale rules, and platform limitations. Ambiguous assumptions are a major source of production incidents because teammates run the same logic under different defaults. Use structured logs around critical branches and external calls so debugging does not require ad hoc reproduction. Logs should include identifiers and concise context, but avoid sensitive payloads.

For recurring jobs or frequently executed code paths, add observability and guardrails. Define simple success metrics, retry boundaries, and explicit rollback or fallback behavior. Silent retries with no upper limit can hide systemic failures and increase downstream impact. Keep a lightweight pre-deploy checklist in source control so changes remain auditable and repeatable across environments.

text
1release_checklist:
2  - tests cover edge cases and failure paths
3  - runtime and dependency versions documented
4  - logs/metrics confirm expected execution path
5  - retries and timeouts are bounded
6  - rollback or fallback plan is defined

Teams that treat these checks as part of the default implementation workflow usually spend less time on incident triage and more time shipping stable improvements.

Common Pitfalls

  • Assuming configparser automatically parses list types.
  • Splitting on commas when values themselves may contain commas.
  • Duplicating parsing logic and creating inconsistent behavior.
  • Missing fallback handling for optional list settings.
  • Skipping validation and surfacing low-level parse errors to users.

Summary

configparser can handle lists effectively when you define a clear encoding convention and parse consistently. Comma-separated strings work for simple lists; JSON strings are safer for complex values. Central parsing helpers, defaults, and validation make INI-based configuration robust in production.


Course illustration
Course illustration

All Rights Reserved.