Skip to content

Commit f4c00d4

Browse files
committed
gh-161926: Honor overridden __float__ in complex()
1 parent 2c2d801 commit f4c00d4

3 files changed

Lines changed: 30 additions & 3 deletions

File tree

‎Lib/test/test_complex.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -711,6 +711,28 @@ def __complex__(self):
711711
check(complex(complex1(1j)), 0.0, 2.0)
712712
self.assertRaises(TypeError, complex, complex2(1j))
713713

714+
def test_constructor_float_subclass(self):
715+
class FloatSubclass(float):
716+
def __float__(self):
717+
return 42.0
718+
719+
value = FloatSubclass(1.0)
720+
for cls in complex, ComplexSubclass:
721+
with self.subTest(cls=cls):
722+
self.assertEqual(cls(value), 42+0j)
723+
self.assertEqual(cls(real=value), 42+0j)
724+
self.assertEqual(cls(value, 0), 42+0j)
725+
726+
def test_constructor_float_subclass_errors(self):
727+
class FloatSubclass(float):
728+
def __float__(self):
729+
raise ValueError('float conversion failed')
730+
731+
for cls in complex, ComplexSubclass:
732+
with self.subTest(cls=cls):
733+
with self.assertRaisesRegex(ValueError, 'float conversion failed'):
734+
cls(FloatSubclass(1.0))
735+
714736
def test___complex__(self):
715737
z = 3 + 4j
716738
self.assertEqual(z.__complex__(), z)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :class:`complex` ignoring an overridden :meth:`~object.__float__` method of a
2+
:class:`float` subclass when called with a single positional argument.

‎Objects/complexobject.c‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1176,10 +1176,13 @@ actual_complex_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
11761176
/* The argument really is entirely real, and contributes
11771177
nothing in the imaginary direction.
11781178
Just treat it as a double. */
1179-
double r = PyFloat_AsDouble(arg);
1180-
if (r != -1.0 || !PyErr_Occurred()) {
1181-
res = complex_subtype_from_doubles(type, r, 0);
1179+
tmp = PyNumber_Float(arg);
1180+
if (tmp == NULL) {
1181+
return NULL;
11821182
}
1183+
double r = PyFloat_AS_DOUBLE(tmp);
1184+
Py_DECREF(tmp);
1185+
res = complex_subtype_from_doubles(type, r, 0);
11831186
}
11841187
else {
11851188
PyErr_Format(PyExc_TypeError,

0 commit comments

Comments
 (0)