Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Lib/test/test_complex.py
Original file line number Diff line number Diff line change
Expand Up @@ -711,6 +711,28 @@ def __complex__(self):
check(complex(complex1(1j)), 0.0, 2.0)
self.assertRaises(TypeError, complex, complex2(1j))

def test_constructor_float_subclass(self):
class FloatSubclass(float):
def __float__(self):
return 42.0

value = FloatSubclass(1.0)
for cls in complex, ComplexSubclass:
with self.subTest(cls=cls):
self.assertEqual(cls(value), 42+0j)
self.assertEqual(cls(real=value), 42+0j)
self.assertEqual(cls(value, 0), 42+0j)

def test_constructor_float_subclass_errors(self):
class FloatSubclass(float):
def __float__(self):
raise ValueError('float conversion failed')

for cls in complex, ComplexSubclass:
with self.subTest(cls=cls):
with self.assertRaisesRegex(ValueError, 'float conversion failed'):
cls(FloatSubclass(1.0))

def test___complex__(self):
z = 3 + 4j
self.assertEqual(z.__complex__(), z)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :class:`complex` ignoring an overridden :meth:`~object.__float__` method of a
:class:`float` subclass when called with a single positional argument.
9 changes: 6 additions & 3 deletions Objects/complexobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1176,10 +1176,13 @@ actual_complex_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
/* The argument really is entirely real, and contributes
nothing in the imaginary direction.
Just treat it as a double. */
double r = PyFloat_AsDouble(arg);
if (r != -1.0 || !PyErr_Occurred()) {
res = complex_subtype_from_doubles(type, r, 0);
tmp = PyNumber_Float(arg);
if (tmp == NULL) {
return NULL;
}
double r = PyFloat_AS_DOUBLE(tmp);
Py_DECREF(tmp);
res = complex_subtype_from_doubles(type, r, 0);
}
else {
PyErr_Format(PyExc_TypeError,
Expand Down
Loading