Python conversion functions construct a selected representation from an accepted input, but their accepted forms can exceed an application’s wire grammar.
Python type conversion: parsing success is not field validity
Operation contract
The quantity protocol permits one to three ASCII digits and a maximum of 200. It validates that text before calling int. Built-in int would also accept forms such as surrounding whitespace and a sign, which this wire field rejects. Converting a float to int truncates toward zero rather than checking that the original number was an exact integer.
Failure and ownership boundary
The parser rejects boolean objects, nontext input and non-ASCII decimal characters. Decimal amounts and timestamps need their own grammar and rounding or timezone policies. Catching every conversion failure as zero would conceal rejected input. Python Decimal money: parse decimal text and choose rounding explicitly and Python datetime: require an offset before comparing timestamps keep those contracts separate.
Working program
import re
def parse_quantity(text):
if not isinstance(text, str) or re.fullmatch(r"[0-9]{1,3}", text) is None:
raise ValueError("quantity grammar rejected")
quantity = int(text)
if quantity > 200:
raise ValueError("quantity budget exceeded")
return quantity
print(parse_quantity("125"))
print("builtin accepts sign:", int(" +3 "))
print("float truncation:", int(-3.8))
for text in ("+3", " 3", "3", True, "201"):
try:
parse_quantity(text)
except ValueError:
print("rejected")Output
125
builtin accepts sign: 3
float truncation: -3
rejected
rejected
rejected
rejected
rejectedCosts and limits
This grammar bounds text to three characters, so validation and conversion perform bounded work. Large integer text needs a reception budget and interpreter-specific digit-limit awareness before conversion. A numeric type annotation performs none of these runtime checks.
Common Mistakes
- Check the declared grammar before converting.
- Truncation is not proof that a received float represented an integer.
Connected lessons
Python input and output: separate parsing from terminal I/O, Python Decimal money: parse decimal text and choose rounding explicitly, Python type hints: annotations do not enforce runtime arguments.
