diff options
author | Alex Martelli <aleaxit@gmail.com> | 2007-08-22 23:21:33 (GMT) |
---|---|---|
committer | Alex Martelli <aleaxit@gmail.com> | 2007-08-22 23:21:33 (GMT) |
commit | ae211f9abf811a28808667450109ca8e2ea53b49 (patch) | |
tree | 5cca7820eb0caa839945420add7fd27d1a63660f /Python | |
parent | 1dd46a048f4afd9a3bc1e3c9c1603d26f2e33e27 (diff) | |
download | cpython-ae211f9abf811a28808667450109ca8e2ea53b49.zip cpython-ae211f9abf811a28808667450109ca8e2ea53b49.tar.gz cpython-ae211f9abf811a28808667450109ca8e2ea53b49.tar.bz2 |
Implement the round functionality for PEP 3141, and add tests for it.
Diffstat (limited to 'Python')
-rw-r--r-- | Python/bltinmodule.c | 28 |
1 files changed, 26 insertions, 2 deletions
diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index 2c163a1..b55dd51 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -1378,10 +1378,34 @@ builtin_round(PyObject *self, PyObject *args, PyObject *kwds) int ndigits = 0; int i; static char *kwlist[] = {"number", "ndigits", 0}; + PyObject* real; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|i:round", - kwlist, &number, &ndigits)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i:round", + kwlist, &real, &ndigits)) return NULL; + + if (ndigits == 0) { + PyObject *res; + PyObject *d = PyObject_GetAttrString(real, "__round__"); + if (d == NULL && !PyFloat_Check(real)) { + PyErr_SetString(PyExc_TypeError, + "round() argument must have __round__ attribute or be a float"); + return NULL; + } + if (d == NULL) { + PyErr_Clear(); + } else { + res = PyObject_CallFunction(d, ""); + Py_DECREF(d); + return res; + } + } else if (!PyFloat_Check(real)) { + PyErr_SetString(PyExc_TypeError, + "round() argument must have __round__ attribute or be a float"); + return NULL; + } + + number = PyFloat_AsDouble(real); f = 1.0; i = abs(ndigits); while (--i >= 0) |