Mercurial > cpython-lru_cache-weakref
diff Python/bltinmodule.c @ 42718:7fe2848fd41d
Implement the round functionality for PEP 3141, and add tests for it.
| author | Alex Martelli <aleaxit@gmail.com> |
|---|---|
| date | Wed, 22 Aug 2007 23:21:33 +0000 |
| parents | aad17b1ab0c9 |
| children | 077fe7860cc9 |
line wrap: on
line diff
--- a/Python/bltinmodule.c Wed Aug 22 23:05:23 2007 +0000 +++ b/Python/bltinmodule.c Wed Aug 22 23:21:33 2007 +0000 @@ -1378,10 +1378,34 @@ 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)
