bpo-36781: Optimize sum() for bools. (#13074)
* Optimize sum() for bools. * Fix sum([], False). * Add a NEWS entry.
This commit is contained in:
parent
c1d8c1cb8e
commit
88bdb9280b
|
@ -1373,6 +1373,24 @@ class BuiltinTest(unittest.TestCase):
|
|||
|
||||
self.assertEqual(sum(range(10), 1000), 1045)
|
||||
self.assertEqual(sum(range(10), start=1000), 1045)
|
||||
self.assertEqual(sum(range(10), 2**31-5), 2**31+40)
|
||||
self.assertEqual(sum(range(10), 2**63-5), 2**63+40)
|
||||
|
||||
self.assertEqual(sum(i % 2 != 0 for i in range(10)), 5)
|
||||
self.assertEqual(sum((i % 2 != 0 for i in range(10)), 2**31-3),
|
||||
2**31+2)
|
||||
self.assertEqual(sum((i % 2 != 0 for i in range(10)), 2**63-3),
|
||||
2**63+2)
|
||||
self.assertIs(sum([], False), False)
|
||||
|
||||
self.assertEqual(sum(i / 2 for i in range(10)), 22.5)
|
||||
self.assertEqual(sum((i / 2 for i in range(10)), 1000), 1022.5)
|
||||
self.assertEqual(sum((i / 2 for i in range(10)), 1000.25), 1022.75)
|
||||
self.assertEqual(sum([0.5, 1]), 1.5)
|
||||
self.assertEqual(sum([1, 0.5]), 1.5)
|
||||
self.assertEqual(repr(sum([-0.0])), '0.0')
|
||||
self.assertEqual(repr(sum([-0.0], -0.0)), '-0.0')
|
||||
self.assertEqual(repr(sum([], -0.0)), '-0.0')
|
||||
|
||||
self.assertRaises(TypeError, sum)
|
||||
self.assertRaises(TypeError, sum, 42)
|
||||
|
@ -1384,6 +1402,9 @@ class BuiltinTest(unittest.TestCase):
|
|||
self.assertRaises(TypeError, sum, [[1], [2], [3]])
|
||||
self.assertRaises(TypeError, sum, [{2:3}])
|
||||
self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})
|
||||
self.assertRaises(TypeError, sum, [], '')
|
||||
self.assertRaises(TypeError, sum, [], b'')
|
||||
self.assertRaises(TypeError, sum, [], bytearray())
|
||||
|
||||
class BadSeq:
|
||||
def __getitem__(self, index):
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
:func:`sum` has been optimized for boolean values.
|
|
@ -2342,7 +2342,7 @@ builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
|
|||
return NULL;
|
||||
return PyLong_FromLong(i_result);
|
||||
}
|
||||
if (PyLong_CheckExact(item)) {
|
||||
if (PyLong_CheckExact(item) || PyBool_Check(item)) {
|
||||
long b = PyLong_AsLongAndOverflow(item, &overflow);
|
||||
if (overflow == 0 &&
|
||||
(i_result >= 0 ? (b <= LONG_MAX - i_result)
|
||||
|
@ -2390,7 +2390,7 @@ builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
|
|||
Py_DECREF(item);
|
||||
continue;
|
||||
}
|
||||
if (PyLong_CheckExact(item)) {
|
||||
if (PyLong_Check(item)) {
|
||||
long value;
|
||||
int overflow;
|
||||
value = PyLong_AsLongAndOverflow(item, &overflow);
|
||||
|
|
Loading…
Reference in New Issue