Preserve empty assignment values with str.partition
An option such as note= can deliberately clear a value, while note may be malformed input. Splitting on the first equals sign with str.partition() keeps that distinction visible in the returned separator.
Set up
Tested on Linux with CPython 3.12.14. Use Bash, Python 3.12 or newer, a text editor, and the mktemp, rm and rmdir utilities. No packages or network access are needed. Keep the same terminal open and stop if setup fails. Run without -O so the assertions remain enabled.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as parse_assignment.py:
def parse_assignment(text):
name, separator, value = text.partition("=")
if not separator:
raise ValueError("missing equals sign")
if not name:
raise ValueError("empty name")
return name, value
for text in ("mode=fast", "note=", "expression=a=b", "mode", "=fast"):
try:
pair = parse_assignment(text)
except ValueError as error:
print(f"{text!r}: rejected ({error})")
else:
print(f"{text!r}: {pair!r}")
assert parse_assignment("note=") == ("note", "")
assert parse_assignment("expression=a=b") == ("expression", "a=b")
assert parse_assignment(" name = value ") == (" name ", " value ")Run:
python3 -B parse_assignment.pyObserved output:
'mode=fast': ('mode', 'fast')
'note=': ('note', '')
'expression=a=b': ('expression', 'a=b')
'mode': rejected (missing equals sign)
'=fast': rejected (empty name)Check the separator before the value
The parser accepts an empty value because the separator is present. It rejects the name-only input because no separator was found. Splitting stops at the first equals sign, so additional equals signs remain part of the value.
The partition reference describes its three-part result: text before the separator, the separator itself, and text after it. An absent separator produces empty second and third parts. Testing the value alone would therefore confuse a missing delimiter with an explicitly empty value.
The second check applies this parser’s separate rule that names cannot be empty. Both rejected cases are intentional and caught in the example. Empty values remain valid; applications that forbid them need an additional rule.
Keep whitespace and grammar choices explicit
This parser preserves whitespace. The final assertion shows spaces remaining in both the name and value. Trim only when the input format defines that behavior; removing spaces from every value can change meaningful data.
The input is one in-memory string. There is no quote handling, escape processing, multiline syntax, or duplicate-name detection across several assignments. Do not use this small parser as a replacement for a complete configuration format such as TOML. It only implements a name, the first equals sign, and the remaining value.
Clean up
Remove the saved file and empty scratch directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- parse_assignment.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.