Skip to content

Commit f9e53a5

Browse files
maurycyvstinner
andauthored
gh-162477: Add PyLong_AsDouble() fast-path for exact ints in PyFloat_AsDouble() (#162478)
Co-authored-by: Victor Stinner <vstinner@python.org>
1 parent a46c65c commit f9e53a5

3 files changed

Lines changed: 12 additions & 0 deletions

File tree

‎Lib/test/test_capi/test_float.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,12 +103,17 @@ class BadFloat3:
103103
def __float__(self):
104104
raise RuntimeError
105105

106+
class IntSubclass(int):
107+
def __float__(self):
108+
return 4.25
109+
106110
self.assertEqual(asdouble(4.25), 4.25)
107111
self.assertEqual(asdouble(-1.0), -1.0)
108112
self.assertEqual(asdouble(42), 42.0)
109113
self.assertEqual(asdouble(-1), -1.0)
110114
self.assertEqual(asdouble(2**1000), float(2**1000))
111115

116+
self.assertEqual(asdouble(IntSubclass(42)), 4.25)
112117
self.assertEqual(asdouble(FloatSubclass(4.25)), 4.25)
113118
self.assertEqual(asdouble(FloatSubclass2(4.25)), 4.25)
114119
self.assertEqual(asdouble(Index()), 99.)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Speed up :c:func:`PyFloat_AsDouble` for exact :class:`int` arguments. Patch by
2+
Maurycy Pawłowski-Wieroński.

‎Objects/floatobject.c‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,11 @@ PyFloat_AsDouble(PyObject *op)
260260
return PyFloat_AS_DOUBLE(op);
261261
}
262262

263+
// int subclass can override __float__() method
264+
if (PyLong_CheckExact(op)) {
265+
return PyLong_AsDouble(op);
266+
}
267+
263268
nb = Py_TYPE(op)->tp_as_number;
264269
if (nb == NULL || nb->nb_float == NULL) {
265270
if (nb && nb->nb_index) {

0 commit comments

Comments
 (0)