@@ -1798,6 +1798,66 @@ PyDoc_STRVAR(vars_doc,
17981798Without arguments, equivalent to locals().\n\
17991799With an argument, equivalent to object.__dict__." );
18001800
1801+
1802+ static PyObject *
1803+ builtin_sum (PyObject * self , PyObject * args )
1804+ {
1805+ PyObject * seq ;
1806+ PyObject * result = NULL ;
1807+ PyObject * temp , * item , * iter ;
1808+
1809+ if (!PyArg_ParseTuple (args , "O|O:sum" , & seq , & result ))
1810+ return NULL ;
1811+
1812+ iter = PyObject_GetIter (seq );
1813+ if (iter == NULL )
1814+ return NULL ;
1815+
1816+ if (result == NULL ) {
1817+ result = PyInt_FromLong (0 );
1818+ if (result == NULL ) {
1819+ Py_DECREF (iter );
1820+ return NULL ;
1821+ }
1822+ } else {
1823+ /* reject string values for 'start' parameter */
1824+ if (PyObject_TypeCheck (result , & PyBaseString_Type )) {
1825+ PyErr_SetString (PyExc_TypeError ,
1826+ "can't sum strings [use ''.join(seq) instead]" );
1827+ Py_DECREF (result );
1828+ Py_DECREF (iter );
1829+ return NULL ;
1830+ }
1831+ }
1832+
1833+ for (;;) {
1834+ item = PyIter_Next (iter );
1835+ if (item == NULL ) {
1836+ /* error, or end-of-sequence */
1837+ if (PyErr_Occurred ()) {
1838+ Py_DECREF (result );
1839+ result = NULL ;
1840+ }
1841+ break ;
1842+ }
1843+ temp = PyNumber_Add (result , item );
1844+ Py_DECREF (result );
1845+ Py_DECREF (item );
1846+ result = temp ;
1847+ if (result == NULL )
1848+ break ;
1849+ }
1850+ Py_DECREF (iter );
1851+ return result ;
1852+ }
1853+
1854+ PyDoc_STRVAR (sum_doc ,
1855+ "sum(sequence, start=0) -> value\n\
1856+ \n\
1857+ Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
1858+ of parameter 'start'. When the sequence is empty, returns start." );
1859+
1860+
18011861static PyObject *
18021862builtin_isinstance (PyObject * self , PyObject * args )
18031863{
@@ -2001,6 +2061,7 @@ static PyMethodDef builtin_methods[] = {
20012061 {"repr" , builtin_repr , METH_O , repr_doc },
20022062 {"round" , builtin_round , METH_VARARGS , round_doc },
20032063 {"setattr" , builtin_setattr , METH_VARARGS , setattr_doc },
2064+ {"sum" , builtin_sum , METH_VARARGS , sum_doc },
20042065#ifdef Py_USING_UNICODE
20052066 {"unichr" , builtin_unichr , METH_VARARGS , unichr_doc },
20062067#endif
0 commit comments