Drop redundant exception type prefix from float-to-int error messages (#7763)

CPython raises `OverflowError("cannot convert float infinity to integer")`
and `ValueError("cannot convert float NaN to integer")` from
`Objects/floatobject.c::float___trunc___impl` and friends. The exception
type name is added by Python's traceback display layer; the message
itself should not duplicate it.

`try_to_bigint` was producing
`OverflowError("OverflowError: cannot convert ...")` etc., which made
`repr(e)` and any code path that inspects `str(e)` diverge from CPython.

Affects all 5 callers of `try_to_bigint`: `__int__`, `__floor__`,
`__ceil__`, `__round__` (no-arg), `__trunc__` — i.e. `int(x)`,
`math.floor/ceil/trunc(x)`, `round(x)` for non-finite floats.

Verified byte-identical with CPython 3.14.4 across 14 affected sites.
This commit is contained in:
Changjoon authored and GitHub committed 2026-05-04 10:24:08 +09:00
1 parent eb99a8ecf1
commit 181e4e7124
2 files changed
+34 -3

No files matched your search

+2 -3
View File
@@ -131,10 +131,9 @@ pub fn try_to_bigint(value: f64, vm: &VirtualMachine) -> PyResult<BigInt> {
Some(int) => Ok(int),
None => {
if value.is_infinite() {
Err(vm
.new_overflow_error("OverflowError: cannot convert float infinity to integer"))
Err(vm.new_overflow_error("cannot convert float infinity to integer"))
} else if value.is_nan() {
Err(vm.new_value_error("ValueError: cannot convert float NaN to integer"))
Err(vm.new_value_error("cannot convert float NaN to integer"))
} else {
// unreachable unless BigInt has a bug
unreachable!(
+32
View File
@@ -517,3 +517,35 @@ assert_raises(ValueError, lambda: float("._0"))
assert 3.0 % -2.0 == -1.0
assert -3.0 % 2.0 == 1.0
# Float-to-int conversion error wording matches CPython exactly. The
# error class name is added by Python's exception display layer; the
# message itself must not duplicate it.
def _check_msg(call, exc_type, expected_msg):
try:
call()
except exc_type as e:
assert str(e) == expected_msg, repr(e)
else:
raise AssertionError(f"expected {exc_type.__name__}")
_check_msg(lambda: int(INF), OverflowError, "cannot convert float infinity to integer")
_check_msg(lambda: int(NINF), OverflowError, "cannot convert float infinity to integer")
_check_msg(lambda: int(NAN), ValueError, "cannot convert float NaN to integer")
_check_msg(
lambda: round(INF), OverflowError, "cannot convert float infinity to integer"
)
_check_msg(lambda: round(NAN), ValueError, "cannot convert float NaN to integer")
_check_msg(
lambda: math.floor(INF), OverflowError, "cannot convert float infinity to integer"
)
_check_msg(lambda: math.ceil(NAN), ValueError, "cannot convert float NaN to integer")
_check_msg(
lambda: math.trunc(INF), OverflowError, "cannot convert float infinity to integer"
)
_check_msg(
lambda: INF.__int__(), OverflowError, "cannot convert float infinity to integer"
)
_check_msg(lambda: NAN.__floor__(), ValueError, "cannot convert float NaN to integer")