summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEzio Melotti <ezio.melotti@gmail.com>2012-11-03 21:19:06 +0200
committerEzio Melotti <ezio.melotti@gmail.com>2012-11-03 21:19:06 +0200
commit9fcb7afc844f13cc4846f9315474bb1a0ced742e (patch)
treeafd3b50418994137edc57b9de2ce8ef6630740e2
parent969fe27b90a54dfcb9319f3dc0b0f38913d1ce63 (diff)
downloadcpython-9fcb7afc844f13cc4846f9315474bb1a0ced742e.tar.gz
#8401: assigning an int to a bytearray slice (e.g. b[3:4] = 5) now raises an error.
-rw-r--r--Lib/test/test_bytes.py18
-rw-r--r--Misc/NEWS3
-rw-r--r--Objects/bytearrayobject.c6
3 files changed, 27 insertions, 0 deletions
diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py
index 5eab8f5561..89e22740fc 100644
--- a/Lib/test/test_bytes.py
+++ b/Lib/test/test_bytes.py
@@ -705,6 +705,24 @@ class ByteArrayTest(BaseBytesTest):
b[3:0] = [42, 42, 42]
self.assertEqual(b, bytearray([0, 1, 2, 42, 42, 42, 3, 4, 5, 6, 7, 8, 9]))
+ b[3:] = b'foo'
+ self.assertEqual(b, bytearray([0, 1, 2, 102, 111, 111]))
+
+ b[:3] = memoryview(b'foo')
+ self.assertEqual(b, bytearray([102, 111, 111, 102, 111, 111]))
+
+ b[3:4] = []
+ self.assertEqual(b, bytearray([102, 111, 111, 111, 111]))
+
+ for elem in [5, -5, 0, int(10e20), 'str', 2.3,
+ ['a', 'b'], [b'a', b'b'], [[]]]:
+ with self.assertRaises(TypeError):
+ b[3:4] = elem
+
+ for elem in [[254, 255, 256], [-256, 9000]]:
+ with self.assertRaises(ValueError):
+ b[3:4] = elem
+
def test_extended_set_del_slice(self):
indices = (0, None, 1, 3, 19, 300, 1<<333, -1, -2, -31, -300)
for start in indices:
diff --git a/Misc/NEWS b/Misc/NEWS
index ed35c82e53..1af684cf7b 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,9 @@ What's New in Python 3.2.4
Core and Builtins
-----------------
+- Issue #8401: assigning an int to a bytearray slice (e.g. b[3:4] = 5) now
+ raises an error.
+
- Issue #16345: Fix an infinite loop when ``fromkeys`` on a dict subclass
received a nonempty dict from the constructor.
diff --git a/Objects/bytearrayobject.c b/Objects/bytearrayobject.c
index 55b4df638a..164c1cf3ca 100644
--- a/Objects/bytearrayobject.c
+++ b/Objects/bytearrayobject.c
@@ -589,6 +589,12 @@ bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *valu
needed = 0;
}
else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
+ if (PyNumber_Check(values) || PyUnicode_Check(values)) {
+ PyErr_SetString(PyExc_TypeError,
+ "can assign only bytes, buffers, or iterables "
+ "of ints in range(0, 256)");
+ return -1;
+ }
/* Make a copy and call this function recursively */
int err;
values = PyByteArray_FromObject(values);