Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f4abc7b

Browse files
author
Stefan Krah
committed
Issue #16431: Use the type information when constructing a Decimal subtype
from a Decimal argument.
1 parent 33363f4 commit f4abc7b

3 files changed

Lines changed: 35 additions & 2 deletions

File tree

Lib/test/test_decimal.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2047,6 +2047,11 @@ class MyDecimal(Decimal):
20472047
self.assertIs(type(d), MyDecimal)
20482048
self.assertEqual(d, d1)
20492049

2050+
a = Decimal('1.0')
2051+
b = MyDecimal(a)
2052+
self.assertIs(type(b), MyDecimal)
2053+
self.assertEqual(a, b)
2054+
20502055
def test_implicit_context(self):
20512056
Decimal = self.decimal.Decimal
20522057
getcontext = self.decimal.getcontext

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,9 @@ Core and Builtins
8080
Library
8181
-------
8282

83+
- Issue #16431: Use the type information when constructing a Decimal subtype
84+
from a Decimal argument.
85+
8386
- Issue #16350: zlib.Decompress.decompress() now accumulates data from
8487
successive calls after EOF in unused_data, instead of only saving the argument
8588
to the last call. Patch by Serhiy Storchaka.

Modules/_decimal/_decimal.c

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2338,6 +2338,32 @@ PyDecType_FromFloat(PyTypeObject *type, PyObject *v,
23382338
return dec;
23392339
}
23402340

2341+
/* Return a new PyDecObject (subtype) from a Decimal. */
2342+
static PyObject *
2343+
PyDecType_FromDecimalExact(PyTypeObject *type, PyObject *v, PyObject *context)
2344+
{
2345+
PyObject *dec;
2346+
uint32_t status = 0;
2347+
2348+
if (type == &PyDec_Type) {
2349+
Py_INCREF(v);
2350+
return v;
2351+
}
2352+
2353+
dec = PyDecType_New(type);
2354+
if (dec == NULL) {
2355+
return NULL;
2356+
}
2357+
2358+
mpd_qcopy(MPD(dec), MPD(v), &status);
2359+
if (dec_addstatus(context, status)) {
2360+
Py_DECREF(dec);
2361+
return NULL;
2362+
}
2363+
2364+
return dec;
2365+
}
2366+
23412367
static PyObject *
23422368
sequence_as_tuple(PyObject *v, PyObject *ex, const char *mesg)
23432369
{
@@ -2642,8 +2668,7 @@ PyDecType_FromObjectExact(PyTypeObject *type, PyObject *v, PyObject *context)
26422668
return PyDecType_FromSsizeExact(type, 0, context);
26432669
}
26442670
else if (PyDec_Check(v)) {
2645-
Py_INCREF(v);
2646-
return v;
2671+
return PyDecType_FromDecimalExact(type, v, context);
26472672
}
26482673
else if (PyUnicode_Check(v)) {
26492674
return PyDecType_FromUnicodeExactWS(type, v, context);

0 commit comments

Comments
 (0)