Skip to content

Commit 6817c59

Browse files
author
Stefan Krah
committed
Issue #27006: from_float(): call the subclass' __new__() and __init__().
1 parent 2275e62 commit 6817c59

2 files changed

Lines changed: 12 additions & 3 deletions

File tree

Lib/test/test_decimal.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2491,14 +2491,17 @@ def test_from_float(self):
24912491
Decimal = self.decimal.Decimal
24922492

24932493
class MyDecimal(Decimal):
2494-
pass
2494+
def __init__(self, _):
2495+
self.x = 'y'
24952496

24962497
self.assertTrue(issubclass(MyDecimal, Decimal))
24972498

24982499
r = MyDecimal.from_float(0.1)
24992500
self.assertEqual(type(r), MyDecimal)
25002501
self.assertEqual(str(r),
25012502
'0.1000000000000000055511151231257827021181583404541015625')
2503+
self.assertEqual(r.x, 'y')
2504+
25022505
bigint = 12345678901234567890123456789
25032506
self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
25042507
self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan())

Modules/_decimal/_decimal.c

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2630,12 +2630,18 @@ PyDecType_FromSequenceExact(PyTypeObject *type, PyObject *v,
26302630

26312631
/* class method */
26322632
static PyObject *
2633-
dec_from_float(PyObject *dec, PyObject *pyfloat)
2633+
dec_from_float(PyObject *type, PyObject *pyfloat)
26342634
{
26352635
PyObject *context;
2636+
PyObject *result;
26362637

26372638
CURRENT_CONTEXT(context);
2638-
return PyDecType_FromFloatExact((PyTypeObject *)dec, pyfloat, context);
2639+
result = PyDecType_FromFloatExact(&PyDec_Type, pyfloat, context);
2640+
if (!PyDec_CheckExact(type) && result != NULL) {
2641+
Py_SETREF(result, PyObject_CallFunctionObjArgs(type, result, NULL));
2642+
}
2643+
2644+
return result;
26392645
}
26402646

26412647
/* create_decimal_from_float */

0 commit comments

Comments
 (0)