"""Strict numeric coercion for fixed-width tax-return wire fields."""from__future__importannotationsimportrefromdecimalimportDecimal,InvalidOperation_FIXED_WIDTH_DECIMAL_RE=re.compile(r"^-?[0-9]+(?:\.[0-9]+)?$")
[docs]defcoerce_fixed_width_decimal(value:object)->Decimal:"""Return a finite exact decimal without guessing or lossy float conversion. Fixed-width filing values are already typed application values or canonical machine-authored strings. Whitespace, exponent notation, leading plus, booleans, and binary floats are therefore refusals rather than alternate spellings. """ifisinstance(value,(bool,float)):raiseValueError("fixed-width numeric values cannot be boolean or float")ifisinstance(value,Decimal):parsed=valueelifisinstance(value,int):parsed=Decimal(value)elifisinstance(value,str)and_FIXED_WIDTH_DECIMAL_RE.fullmatch(value)isnotNone:try:parsed=Decimal(value)exceptInvalidOperationasexc:raiseValueError("fixed-width numeric value is not a decimal")fromexcelse:raiseValueError("fixed-width numeric value must be an int, Decimal, or canonical decimal string")ifnotparsed.is_finite():raiseValueError("fixed-width numeric value must be finite")returnparsed