@@ -2828,6 +2828,51 @@ dec_from_float(PyObject *type, PyObject *pyfloat)
28282828 return result ;
28292829}
28302830
2831+ /* 'v' can have any numeric type accepted by the Decimal constructor. Attempt
2832+ an exact conversion. If the result does not meet the restrictions
2833+ for an mpd_t, fail with InvalidOperation. */
2834+ static PyObject *
2835+ PyDecType_FromNumberExact (PyTypeObject * type , PyObject * v , PyObject * context )
2836+ {
2837+ decimal_state * state = get_module_state_by_def (type );
2838+ assert (v != NULL );
2839+ if (PyDec_Check (state , v )) {
2840+ return PyDecType_FromDecimalExact (type , v , context );
2841+ }
2842+ else if (PyLong_Check (v )) {
2843+ return PyDecType_FromLongExact (type , v , context );
2844+ }
2845+ else if (PyFloat_Check (v )) {
2846+ if (dec_addstatus (context , MPD_Float_operation )) {
2847+ return NULL ;
2848+ }
2849+ return PyDecType_FromFloatExact (type , v , context );
2850+ }
2851+ else {
2852+ PyErr_Format (PyExc_TypeError ,
2853+ "conversion from %s to Decimal is not supported" ,
2854+ Py_TYPE (v )-> tp_name );
2855+ return NULL ;
2856+ }
2857+ }
2858+
2859+ /* class method */
2860+ static PyObject *
2861+ dec_from_number (PyObject * type , PyObject * number )
2862+ {
2863+ PyObject * context ;
2864+ PyObject * result ;
2865+
2866+ decimal_state * state = get_module_state_by_def ((PyTypeObject * )type );
2867+ CURRENT_CONTEXT (state , context );
2868+ result = PyDecType_FromNumberExact (state -> PyDec_Type , number , context );
2869+ if (type != (PyObject * )state -> PyDec_Type && result != NULL ) {
2870+ Py_SETREF (result , PyObject_CallFunctionObjArgs (type , result , NULL ));
2871+ }
2872+
2873+ return result ;
2874+ }
2875+
28312876/* create_decimal_from_float */
28322877static PyObject *
28332878ctx_from_float (PyObject * context , PyObject * v )
@@ -5017,6 +5062,7 @@ static PyMethodDef dec_methods [] =
50175062
50185063 /* Miscellaneous */
50195064 { "from_float" , dec_from_float , METH_O |METH_CLASS , doc_from_float },
5065+ { "from_number" , dec_from_number , METH_O |METH_CLASS , doc_from_number },
50205066 { "as_tuple" , PyDec_AsTuple , METH_NOARGS , doc_as_tuple },
50215067 { "as_integer_ratio" , dec_as_integer_ratio , METH_NOARGS , doc_as_integer_ratio },
50225068
0 commit comments