Fix the config reader for a settings file
Your task
You asked an AI for a function that reads one setting from a config file. Its first version worked on a clean file and handled nothing else: no comments, no blank lines, no broken lines. The new version reads key=value lines defensively and falls back to a default.
An assistant wrote read_config_value(lines, key, fallback). It is in the editor. It has a bug. Find it and fix it.
Input and output:
lines: the lines of the config file, in order.key: the setting to read.fallback: the value to return when the setting is not found.- Return the setting's value as a string.
Rules the tests check:
- To trim text means to remove spaces, tabs, newlines and carriage returns from both ends, and nothing else.
- Trim
keybefore comparing. - For each line in order: trim it. Skip it if it is empty or starts with
#. - Split the line at its first
=. Skip the line if it has no=. The key is the part before the first=, trimmed. The value is everything after the first=, trimmed. - Skip a line whose key is empty.
- A line matches when its key equals
keyexactly, case included. When several lines match, the last one wins. - Return the value of the last match, even if it is empty. With no match, return
fallbackunchanged.
Examples
read_config_value(lines: list[str], key: str, fallback: str) -> strExample 1
Input
read_config_value(["timeout_ms=250", "retries=3"], "retries", "1")Output
"3"Example 2
Input
read_config_value(["timeout_ms=250"], "retries", "1")Output
"1"Example 3
Input
read_config_value(["# retries=9", "retries= 4 "], "retries", "1")Output
"4"