summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Lib/test/test_builtin.py21
-rw-r--r--Misc/NEWS.d/next/Core and Builtins/2019-05-06-09-59-31.bpo-36781.uocWt6.rst1
-rw-r--r--Python/bltinmodule.c4
3 files changed, 24 insertions, 2 deletions
diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index db2f6cd..7b3c054 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -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):
diff --git a/Misc/NEWS.d/next/Core and Builtins/2019-05-06-09-59-31.bpo-36781.uocWt6.rst b/Misc/NEWS.d/next/Core and Builtins/2019-05-06-09-59-31.bpo-36781.uocWt6.rst
new file mode 100644
index 0000000..2e9dcdc
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2019-05-06-09-59-31.bpo-36781.uocWt6.rst
@@ -0,0 +1 @@
+:func:`sum` has been optimized for boolean values.
diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c
index 3b0d64f..d069f2f 100644
--- a/Python/bltinmodule.c
+++ b/Python/bltinmodule.c
@@ -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);