Parse Key-Value Overrides with Python partition

A build tool accepts overrides such as mode=preview and token=abc==. Splitting on every equals sign destroys the token’s shape. Another subtle mistake is treating label= and label as equivalent, even though one explicitly supplies an empty value and the other omits the required separator.

These examples use Python 3.10 or later. They parse individual strings already received by a program, such as arguments from sys.argv[1:]. The format has one literal separator and no quoting, escaping, variable expansion, or comments of its own.

Split at the First Equals Sign

Run this standalone example:

1
2
3
4
5
for text in ["token=abc==", "label=", "label"]:
    print(text.partition("="))
# ('token', '=', 'abc==')
# ('label', '=', '')
# ('label', '', '')

partition() returns three strings: the part before the first match, the separator itself, and the remainder. When the separator is absent, the first item is the original string and the other two are empty. This gives validation a direct signal for a missing separator. See the Python string reference .

split("=", 1) also preserves later equals signs, but returns a one-item list when the separator is absent. Either method can implement this format; partition() makes the separator check explicit without variable-length unpacking. rpartition() would split at the last match and produce a different key for token=abc==.

Define the Key and Value Contract

Save this helper as overrides.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import re


def parse_override(text):
    if not isinstance(text, str):
        raise TypeError("override must be a string")
    key, separator, value = text.partition("=")
    if not separator:
        raise ValueError("override must contain =")
    if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key) is None:
        raise ValueError("invalid override key")
    return key, value

Keys follow a deliberately narrow ASCII identifier rule. Values may be empty and retain every character after the first equals sign, including spaces and further equals signs. The helper performs no trimming or case conversion. The regular expression reference explains why fullmatch() checks the whole key.

The separator check comes before key validation. An empty separator from partition() means the delimiter was absent; an empty value does not. Because the delimiter is a fixed nonempty literal here, its truth value is sufficient for the check.

Reject Duplicate Keys While Collecting Overrides

Append this function to overrides.py:

1
2
3
4
5
6
7
8
def collect_overrides(items):
    result = {}
    for item in items:
        key, value = parse_override(item)
        if key in result:
            raise ValueError(f"duplicate override key: {key}")
        result[key] = value
    return result

Save this demonstration beside the helper and run it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from overrides import collect_overrides

settings = collect_overrides(iter([
    "mode=preview", "token=abc==", "label=", "message= hello = world ",
]))
print(settings["token"])
print(repr(settings["label"]))
print(repr(settings["message"]))
# abc==
# ''
# ' hello = world '

Using membership rather than result.get(key) catches duplicates even when the first value is empty. Keys are case-sensitive, so Mode and mode remain separate. A malformed item or duplicate raises before the local dictionary is returned. Consuming the input iterator still has effects: items already read cannot be recovered automatically after failure.

Test the Delimiter and Duplicate Boundaries

Save this as test_overrides.py beside the helper and run python test_overrides.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from overrides import collect_overrides, parse_override

for text, expected in [
    ("token=abc==", ("token", "abc==")),
    ("label=", ("label", "")),
    ("_x2==", ("_x2", "=")),
    ("message= hello = world ", ("message", " hello = world ")),
]:
    assert parse_override(text) == expected

for text in ["", "label", "=value", "2mode=x", " mode=x", "mode =x", "a-b=x"]:
    try:
        parse_override(text)
    except ValueError:
        pass
    else:
        raise AssertionError(f"invalid override accepted: {text!r}")

try:
    parse_override(None)
except TypeError:
    pass
else:
    raise AssertionError("non-string override accepted")

try:
    collect_overrides(["label=", "label=again"])
except ValueError as exc:
    assert str(exc) == "duplicate override key: label"
else:
    raise AssertionError("duplicate empty-valued key accepted")

assert collect_overrides([]) == {}
assert collect_overrides(["Mode=A", "mode=B"]) == {"Mode": "A", "mode": "B"}
print("Override parsing checks passed.")

The test pairs an absent delimiter with an explicitly empty value and checks a value made entirely of a delimiter. It also verifies whitespace preservation in values and rejection in keys, so a later cleanup step cannot silently change the format’s identity rules.

Apply Meaning Only After Parsing

The returned values are strings. A consumer must separately validate known keys and convert values according to each setting’s schema. For example, enabled=false contains the nonempty string false; applying bool() to it produces True. Define the accepted boolean spellings explicitly when implementing that setting.

This helper does not parse shell syntax. A shell may remove quotes or expand variables before Python receives arguments. If a value contains spaces, quote the complete argument according to the invoking shell’s rules; those shell quotes are not part of this override grammar.

Likewise, this is not a dotenv or INI reader. Adding comments, quoted values, multiline values, or escapes changes the grammar and needs a suitable parser. For the stated format, keep the first equals sign as the boundary and leave the remainder intact until the setting-specific validation step.