[Python-checkins] cpython: bytes should be verboten in sum() (fixes #12654)

benjamin.peterson python-checkins at python.org
Fri Jul 29 21:24:42 CEST 2011


http://hg.python.org/cpython/rev/7368d0e9b33e
changeset:   71610:7368d0e9b33e
user:        Benjamin Peterson <benjamin at python.org>
date:        Fri Jul 29 14:23:47 2011 -0500
summary:
  bytes should be verboten in sum() (fixes #12654)

files:
  Lib/test/test_builtin.py |  3 +++
  Misc/NEWS                |  2 ++
  Python/bltinmodule.c     |  5 +++++
  3 files changed, 10 insertions(+), 0 deletions(-)


diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -1128,6 +1128,9 @@
         self.assertRaises(TypeError, sum, 42)
         self.assertRaises(TypeError, sum, ['a', 'b', 'c'])
         self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')
+        self.assertRaises(TypeError, sum, [b'a', b'c'], b'')
+        values = [bytearray(b'a'), bytearray(b'b')]
+        self.assertRaises(TypeError, sum, values, bytearray(b''))
         self.assertRaises(TypeError, sum, [[1], [2], [3]])
         self.assertRaises(TypeError, sum, [{2:3}])
         self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,8 @@
 Core and Builtins
 -----------------
 
+- Forbid summing bytes in sum().
+
 - Verify the types of AST strings and identifiers provided by the user before
   compiling them.
 
diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c
--- a/Python/bltinmodule.c
+++ b/Python/bltinmodule.c
@@ -1888,6 +1888,11 @@
             Py_DECREF(iter);
             return NULL;
         }
+        if (PyBytes_Check(result)) {
+            PyErr_SetString(PyExc_TypeError,
+                "sum() can't sum bytes [use b''.join(seq) instead]");
+            return NULL;
+        }
         if (PyByteArray_Check(result)) {
             PyErr_SetString(PyExc_TypeError,
                 "sum() can't sum bytes [use b''.join(seq) instead]");

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list