Batu Lab NotesPractical developer guides

Turn a parser failure into a structured result object

By Batu · English technical notes

Also published in our primary archive.

To turn a parser failure into a structured result object, catch the narrow ValueError raised by int() and return an explicit success or failure mapping. For input '12', this example returns {'ok': True, 'value': 12}. For 'twelve', it returns {'ok': False, 'code': 'not_integer'} rather than None.

Returning None loses information at the boundary: a caller cannot tell whether parsing failed, parsing intentionally produced an optional empty value, or a function forgot to return. A small result object makes the branch visible. The ok key says which shape is active, while value is present only for a converted integer and code is present only for the expected parsing failure. The fixture also keeps the exception boundary tight: only int(text) is inside try. Code added after conversion will therefore not be accidentally relabeled as not_integer.

int() converts compatible strings when called without a base argument and raises ValueError for invalid conversion. This pattern is useful where invalid text is an expected result. It does not preserve the original exception, provide an input position, or support a richer number grammar; add those details if callers need them. The assertions verify the two synthetic inputs and their exact returned shapes.

This example uses no newer API; it runs on supported Python 3 versions.

AI assistance disclosure: this article was drafted with AI assistance and the synthetic example is intended to be run locally.

Source: Python’s error tutorial describes handling exceptions, and the int constructor documentation specifies conversion behavior.

def parse_integer(text):
    try:
        value = int(text)
    except ValueError:
        return {"ok": False, "code": "not_integer"}
    return {"ok": True, "value": value}


valid = parse_integer("12")
invalid = parse_integer("twelve")

assert valid == {"ok": True, "value": 12}
assert invalid == {"ok": False, "code": "not_integer"}
assert "value" not in invalid

print(valid)
print(invalid)
{'ok': True, 'value': 12}
{'ok': False, 'code': 'not_integer'}