Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 86d8b34

Browse files
committed
Implement the trunc builtin for PEP 3141
1 parent a62b45c commit 86d8b34

2 files changed

Lines changed: 36 additions & 0 deletions

File tree

Lib/test/test_builtin.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1515,6 +1515,20 @@ def __getitem__(self, index):
15151515
raise ValueError
15161516
self.assertRaises(ValueError, sum, BadSeq())
15171517

1518+
def test_trunc(self):
1519+
class TestTrunc:
1520+
def __trunc__(self):
1521+
return 23
1522+
1523+
class TestNoTrunc:
1524+
pass
1525+
1526+
self.assertEqual(trunc(TestTrunc()), 23)
1527+
1528+
self.assertRaises(TypeError, trunc)
1529+
self.assertRaises(TypeError, trunc, 1, 2)
1530+
self.assertRaises(TypeError, trunc, TestNoTrunc())
1531+
15181532
def test_tuple(self):
15191533
self.assertEqual(tuple(()), ())
15201534
t0_3 = (0, 1, 2, 3)

Python/bltinmodule.c

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1486,6 +1486,27 @@ PyDoc_STRVAR(vars_doc,
14861486
Without arguments, equivalent to locals().\n\
14871487
With an argument, equivalent to object.__dict__.");
14881488

1489+
static PyObject *
1490+
builtin_trunc(PyObject *self, PyObject *v)
1491+
{
1492+
PyObject *res;
1493+
PyObject *d = PyObject_GetAttrString(v, "__trunc__");
1494+
if (d == NULL) {
1495+
PyErr_SetString(PyExc_TypeError,
1496+
"trunc() argument must have __trunc__ attribute");
1497+
return NULL;
1498+
}
1499+
res = PyObject_CallFunction(d, "");
1500+
Py_DECREF(d);
1501+
return res;
1502+
}
1503+
1504+
PyDoc_STRVAR(trunc_doc,
1505+
"trunc(Real) -> Integral\n\
1506+
\n\
1507+
returns the integral closest to x between 0 and x.");
1508+
1509+
14891510

14901511
static PyObject*
14911512
builtin_sum(PyObject *self, PyObject *args)
@@ -1659,6 +1680,7 @@ static PyMethodDef builtin_methods[] = {
16591680
{"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
16601681
{"sum", builtin_sum, METH_VARARGS, sum_doc},
16611682
{"vars", builtin_vars, METH_VARARGS, vars_doc},
1683+
{"trunc", builtin_trunc, METH_O, trunc_doc},
16621684
{"zip", builtin_zip, METH_VARARGS, zip_doc},
16631685
{NULL, NULL},
16641686
};

0 commit comments

Comments
 (0)