Skip to content
Prev Previous commit
Next Next commit
honor round and capitals context in fallback
  • Loading branch information
belm0 committed Feb 11, 2024
commit dcee58f3f3d5ada666954499ddc455370ddc4705
6 changes: 6 additions & 0 deletions Lib/_pydecimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -3841,6 +3841,12 @@ def __format__(self, specifier, context=None, _localeconv=None):
# of the formatting to the _format_number function
return _format_number(adjusted_sign, intpart, fracpart, exp, spec)

def _fallback_format(self, specifier, rounding, caps):
"""returns `__format__(specifier)` using a temporary context"""
c = Context(rounding=rounding, capitals=caps)
return self.__format__(specifier, c)


def _dec_from_triple(sign, coefficient, exponent, special=False):
"""Create a decimal instance directly, without any validation,
normalization (e.g. removal of leading zeros) or argument
Expand Down
12 changes: 9 additions & 3 deletions Modules/_decimal/_decimal.c
Original file line number Diff line number Diff line change
Expand Up @@ -3370,10 +3370,12 @@ dict_get_item_string(PyObject *dict, const char *key, PyObject **valueobj, const
* https://www.bytereef.org/mpdecimal/doc/libmpdec/assign-convert.html#to-string
*/
static PyObject *
pydec_format(PyObject *dec, PyObject *fmt, decimal_state *state)
pydec_format(PyObject *dec, PyObject *context, PyObject *fmt, decimal_state *state)
{
PyObject *result;
PyObject *pydec;
PyObject *rounding;
PyObject *caps;
PyObject *u;

if (state->PyDecimal == NULL) {
Expand All @@ -3394,7 +3396,11 @@ pydec_format(PyObject *dec, PyObject *fmt, decimal_state *state)
return NULL;
}

result = PyObject_Format(pydec, fmt);
rounding = context_getround(context, NULL);
caps = context_getcapitals(context, NULL);
result = PyObject_CallMethod(pydec, "_fallback_format", "(OOO)", fmt, rounding, caps);
Comment thread
belm0 marked this conversation as resolved.
Outdated
Py_DECREF(rounding);
Py_DECREF(caps);
Py_DECREF(pydec);

if (result == NULL && PyErr_ExceptionMatches(PyExc_ValueError)) {
Expand Down Expand Up @@ -3466,7 +3472,7 @@ dec_format(PyObject *dec, PyObject *args)
PyMem_Free(fmt);
}

return pydec_format(dec, fmtarg, state);
return pydec_format(dec, context, fmtarg, state);
}

if (replace_fillchar) {
Expand Down