Skip to content

Commit 5217328

Browse files
pythongh-121798: Add class method Decimal.from_number() (pythonGH-121801)
It is an alternate constructor which only accepts a single numeric argument. Unlike to Decimal.from_float() it accepts also Decimal. Unlike to the standard constructor, it does not accept strings and tuples.
1 parent 4b358ee commit 5217328

File tree

7 files changed

+122
-0
lines changed

7 files changed

+122
-0
lines changed

Doc/library/decimal.rst

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -598,6 +598,23 @@ Decimal objects
598598

599599
.. versionadded:: 3.1
600600

601+
.. classmethod:: from_number(number)
602+
603+
Alternative constructor that only accepts instances of
604+
:class:`float`, :class:`int` or :class:`Decimal`, but not strings
605+
or tuples.
606+
607+
.. doctest::
608+
609+
>>> Decimal.from_number(314)
610+
Decimal('314')
611+
>>> Decimal.from_number(0.1)
612+
Decimal('0.1000000000000000055511151231257827021181583404541015625')
613+
>>> Decimal.from_number(Decimal('3.14'))
614+
Decimal('3.14')
615+
616+
.. versionadded:: 3.14
617+
601618
.. method:: fma(other, third, context=None)
602619

603620
Fused multiply-add. Return self*other+third with no rounding of the

Doc/whatsnew/3.14.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,12 @@ ctypes
239239
to help match a non-default ABI.
240240
(Contributed by Petr Viktorin in :gh:`97702`.)
241241

242+
decimal
243+
-------
244+
245+
* Add alternative :class:`~decimal.Decimal` constructor
246+
:meth:`Decimal.from_number() <decimal.Decimal.from_number>`.
247+
(Contributed by Serhiy Storchaka in :gh:`121798`.)
242248

243249
dis
244250
---

Lib/_pydecimal.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,21 @@ def __new__(cls, value="0", context=None):
582582

583583
raise TypeError("Cannot convert %r to Decimal" % value)
584584

585+
@classmethod
586+
def from_number(cls, number):
587+
"""Converts a real number to a decimal number, exactly.
588+
589+
>>> Decimal.from_number(314) # int
590+
Decimal('314')
591+
>>> Decimal.from_number(0.1) # float
592+
Decimal('0.1000000000000000055511151231257827021181583404541015625')
593+
>>> Decimal.from_number(Decimal('3.14')) # another decimal instance
594+
Decimal('3.14')
595+
"""
596+
if isinstance(number, (int, Decimal, float)):
597+
return cls(number)
598+
raise TypeError("Cannot convert %r to Decimal" % number)
599+
585600
@classmethod
586601
def from_float(cls, f):
587602
"""Converts a float to a decimal number, exactly.

Lib/test/test_decimal.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -812,6 +812,29 @@ def test_explicit_context_create_from_float(self):
812812
x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
813813
self.assertEqual(x, float(nc.create_decimal(x))) # roundtrip
814814

815+
def test_from_number(self, cls=None):
816+
Decimal = self.decimal.Decimal
817+
if cls is None:
818+
cls = Decimal
819+
820+
def check(arg, expected):
821+
d = cls.from_number(arg)
822+
self.assertIs(type(d), cls)
823+
self.assertEqual(d, expected)
824+
825+
check(314, Decimal(314))
826+
check(3.14, Decimal.from_float(3.14))
827+
check(Decimal('3.14'), Decimal('3.14'))
828+
self.assertRaises(TypeError, cls.from_number, 3+4j)
829+
self.assertRaises(TypeError, cls.from_number, '314')
830+
self.assertRaises(TypeError, cls.from_number, (0, (3, 1, 4), 0))
831+
self.assertRaises(TypeError, cls.from_number, object())
832+
833+
def test_from_number_subclass(self, cls=None):
834+
class DecimalSubclass(self.decimal.Decimal):
835+
pass
836+
self.test_from_number(DecimalSubclass)
837+
815838
def test_unicode_digits(self):
816839
Decimal = self.decimal.Decimal
817840

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Add alternative :class:`~decimal.Decimal` constructor
2+
:meth:`Decimal.from_number() <decimal.Decimal.from_number>`.

Modules/_decimal/_decimal.c

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2857,6 +2857,51 @@ dec_from_float(PyObject *type, PyObject *pyfloat)
28572857
return result;
28582858
}
28592859

2860+
/* 'v' can have any numeric type accepted by the Decimal constructor. Attempt
2861+
an exact conversion. If the result does not meet the restrictions
2862+
for an mpd_t, fail with InvalidOperation. */
2863+
static PyObject *
2864+
PyDecType_FromNumberExact(PyTypeObject *type, PyObject *v, PyObject *context)
2865+
{
2866+
decimal_state *state = get_module_state_by_def(type);
2867+
assert(v != NULL);
2868+
if (PyDec_Check(state, v)) {
2869+
return PyDecType_FromDecimalExact(type, v, context);
2870+
}
2871+
else if (PyLong_Check(v)) {
2872+
return PyDecType_FromLongExact(type, v, context);
2873+
}
2874+
else if (PyFloat_Check(v)) {
2875+
if (dec_addstatus(context, MPD_Float_operation)) {
2876+
return NULL;
2877+
}
2878+
return PyDecType_FromFloatExact(type, v, context);
2879+
}
2880+
else {
2881+
PyErr_Format(PyExc_TypeError,
2882+
"conversion from %s to Decimal is not supported",
2883+
Py_TYPE(v)->tp_name);
2884+
return NULL;
2885+
}
2886+
}
2887+
2888+
/* class method */
2889+
static PyObject *
2890+
dec_from_number(PyObject *type, PyObject *number)
2891+
{
2892+
PyObject *context;
2893+
PyObject *result;
2894+
2895+
decimal_state *state = get_module_state_by_def((PyTypeObject *)type);
2896+
CURRENT_CONTEXT(state, context);
2897+
result = PyDecType_FromNumberExact(state->PyDec_Type, number, context);
2898+
if (type != (PyObject *)state->PyDec_Type && result != NULL) {
2899+
Py_SETREF(result, PyObject_CallFunctionObjArgs(type, result, NULL));
2900+
}
2901+
2902+
return result;
2903+
}
2904+
28602905
/* create_decimal_from_float */
28612906
static PyObject *
28622907
ctx_from_float(PyObject *context, PyObject *v)
@@ -5052,6 +5097,7 @@ static PyMethodDef dec_methods [] =
50525097

50535098
/* Miscellaneous */
50545099
{ "from_float", dec_from_float, METH_O|METH_CLASS, doc_from_float },
5100+
{ "from_number", dec_from_number, METH_O|METH_CLASS, doc_from_number },
50555101
{ "as_tuple", PyDec_AsTuple, METH_NOARGS, doc_as_tuple },
50565102
{ "as_integer_ratio", dec_as_integer_ratio, METH_NOARGS, doc_as_integer_ratio },
50575103

Modules/_decimal/docstrings.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,19 @@ Decimal.from_float(0.1) is not the same as Decimal('0.1').\n\
189189
\n\
190190
\n");
191191

192+
PyDoc_STRVAR(doc_from_number,
193+
"from_number($type, number, /)\n--\n\n\
194+
Class method that converts a real number to a decimal number, exactly.\n\
195+
\n\
196+
>>> Decimal.from_number(314) # int\n\
197+
Decimal('314')\n\
198+
>>> Decimal.from_number(0.1) # float\n\
199+
Decimal('0.1000000000000000055511151231257827021181583404541015625')\n\
200+
>>> Decimal.from_number(Decimal('3.14')) # another decimal instance\n\
201+
Decimal('3.14')\n\
202+
\n\
203+
\n");
204+
192205
PyDoc_STRVAR(doc_fma,
193206
"fma($self, /, other, third, context=None)\n--\n\n\
194207
Fused multiply-add. Return self*other+third with no rounding of the\n\

0 commit comments

Comments
 (0)