Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c64bcbe

Browse files
committed
#8401: assigning an int to a bytearray slice (e.g. b[3:4] = 5) now raises an error.
1 parent 11f3f17 commit c64bcbe

3 files changed

Lines changed: 27 additions & 0 deletions

File tree

Lib/test/test_bytes.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -705,6 +705,24 @@ def test_setslice(self):
705705
b[3:0] = [42, 42, 42]
706706
self.assertEqual(b, bytearray([0, 1, 2, 42, 42, 42, 3, 4, 5, 6, 7, 8, 9]))
707707

708+
b[3:] = b'foo'
709+
self.assertEqual(b, bytearray([0, 1, 2, 102, 111, 111]))
710+
711+
b[:3] = memoryview(b'foo')
712+
self.assertEqual(b, bytearray([102, 111, 111, 102, 111, 111]))
713+
714+
b[3:4] = []
715+
self.assertEqual(b, bytearray([102, 111, 111, 111, 111]))
716+
717+
for elem in [5, -5, 0, int(10e20), 'str', 2.3,
718+
['a', 'b'], [b'a', b'b'], [[]]]:
719+
with self.assertRaises(TypeError):
720+
b[3:4] = elem
721+
722+
for elem in [[254, 255, 256], [-256, 9000]]:
723+
with self.assertRaises(ValueError):
724+
b[3:4] = elem
725+
708726
def test_extended_set_del_slice(self):
709727
indices = (0, None, 1, 3, 19, 300, 1<<333, -1, -2, -31, -300)
710728
for start in indices:

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ What's New in Python 3.2.4
1010
Core and Builtins
1111
-----------------
1212

13+
- Issue #8401: assigning an int to a bytearray slice (e.g. b[3:4] = 5) now
14+
raises an error.
15+
1316
- Issue #16345: Fix an infinite loop when ``fromkeys`` on a dict subclass
1417
received a nonempty dict from the constructor.
1518

Objects/bytearrayobject.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,12 @@ bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *valu
589589
needed = 0;
590590
}
591591
else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
592+
if (PyNumber_Check(values) || PyUnicode_Check(values)) {
593+
PyErr_SetString(PyExc_TypeError,
594+
"can assign only bytes, buffers, or iterables "
595+
"of ints in range(0, 256)");
596+
return -1;
597+
}
592598
/* Make a copy and call this function recursively */
593599
int err;
594600
values = PyByteArray_FromObject(values);

0 commit comments

Comments
 (0)